C语言多线程

文章目录

创建线程

在C语言中创建线程方式如下

#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)

其中,thread为线程指针;attr为线程属性,默认NULLstart_routine为线程运行函数起始地址;arg为运行函数的参数。无参数时使用NULL

如果线程成功创建,函数返回0,否则说明创建失败。

当线程完成工作后,若无需继续存在,则会调用pthread_exit函数。也就是说,这个函数可以显式地退出一个线程。

pthread_exit (status)

实战

下面做一个简单的示例,通过调用多线程来打印数字

//test1.c
#include<stdio.h>
#include<pthread.h>
#define NUM_THREADS 5

void *PrintTh(void *th){
	int i = *((int*)th);
	printf("Hello, I'm thread %d\n", i);
	return 0;
}

int main(){
	int i,ret;
	pthread_t p;
	for(i=0; i<NUM_THREADS; i++){
		printf("create th %d\n",i);
		ret = pthread_create(&p,NULL, PrintTh, (void*)&i);
		if(ret != 0)
			printf("th %d error, code = \n",i);
	}
	pthread_exit(NULL);
	return 0;
}

如果在Linux中使用pthread,需要使用库libpthread.a, 编译时要加-lpthread参数:

gcc test1.c -lpthread -o test1.o ./test1.

运行结果如下


create th 0
create th 1
Hello, I’m thread 1
Hello, I’m thread 2
create th 2
Hello, I’m thread 3
create th 3
create th 4
Hello, I’m thread 4
Hello, I’m thread 4


之所以main函数和printTh输出的值不同,是因为我们传入printTh的参数是一个空指针,这个空指针直接指向了用于循环的i的地址,所以printTh调用i的时候,有时i的取值刚好发生变化,有时尚未发生变化。

由于函数pthread_create接收的传输参数必须为void*,而且只有一个,故当需要传递多个参数时,需要用到结构体。

// test2.c
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define NUM_THREADS 5
 
typedef struct PERSON{
    int id;
    char name;
}Person, *pPerson;

void * PrintTh(void * p)
{
    pPerson tid = (pPerson)p;
    printf("I'm %c ,th %d\n", tid->name,tid->id);
    return 0;
}
 
int main(void)
{
    pthread_t Pthread[NUM_THREADS];
    Person persons[NUM_THREADS];

    int i, ret;
    for (i = 0; i < NUM_THREADS; i++)
    {
        printf("create th %d \n",i);
        persons[i].id = i;
        persons[i].name = 'A'+i%10;
        ret = pthread_create(&Pthread[i], NULL, PrintTh, (void *)&persons[i]);
        if (0 != ret)
        {
            printf("Error: 创建线程失败!\n");
            exit(-1);
        }
    }
    pthread_exit(NULL);
    return 0;
}

输出结果为


create th 0
create th 1
I’m A ,th 0
I’m B ,th 1
create th 2
create th 3
I’m C ,th 2
I’m D ,th 3
create th 4
I’m E ,th 4


### C语言中使用`pthread`创建线程 在C语言中,通过POSIX Threads (pthreads) 库可以方便地管理多线程应用。要创建一个新的线程,主要依赖于 `pthread_create()` 函数[^1]。 #### 使用`pthread_create()`创建线程 该函数原型如下: ```c int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg); ``` - 参数一指向一个 `pthread_t` 类型变量,用于存储新建线程ID; - 参数二通常传入NULL表示采用默认属性; - 参数三是指向线程入口点的指针,即希望在线程启动时执行的任务函数地址; - 参数四则是传递给上述任务函数的数据参数。 下面给出一段简单的例子说明如何利用这些概念来编写一个多线程程序[^3]: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> /* For sleep() */ #include <pthread.h> // 定义线程运行函数 void* thread_function(void *arg){ printf("Thread is running\n"); sleep(1); // 让当前线程休眠一秒以便观察效果 return NULL; } int main(){ int res; pthread_t a_thread; // 创建线程并检查返回状态码 res = pthread_create(&a_thread, NULL, thread_function, NULL); if(res != 0){ perror("Thread creation failed"); exit(EXIT_FAILURE); } // 主线程继续往下走... printf("Main thread continues to run...\n"); // 等待子线程完成后再结束主线程 pthread_join(a_thread, NULL); printf("Sub-thread has finished.\n"); return 0; } ``` 这段代码展示了基本流程:定义好想要让其他线程去做的工作之后,在主进程中调用 `pthread_create()` 来启动新的线程;最后记得要用 `pthread_join()` 阻塞住父进程直到所有子线程都结束了才允许其终止[^4]。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微小冷

请我喝杯咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值