希赛考试网
首页 > 软考 > 软件设计师

linux怎么创建线程

希赛网 2024-03-01 16:46:18

在Linux中,线程是轻量级进程。当一个进程创建线程时,这个进程会产生一个新的执行流,这个新的执行流与原先的执行流并发执行。在多线程的环境中,多个线程共享进程的资源,这样可以大大提高程序的效率。

那么,在Linux中,我们该如何创建线程呢?下面我们从多个角度来分析这个问题。

一、使用pthread库来创建线程

Linux提供了pthread库,我们可以通过调用它的函数来创建线程。下面是一个简单的例子:

```c

#include

#include

#include

void *thread_func(void *arg)

{

printf("This is a new thread.\n");

pthread_exit(NULL);

}

int main()

{

pthread_t tid; //tid为新建线程的标识符

int ret = pthread_create(&tid, NULL, thread_func, NULL);

if (ret != 0) {

printf("Fail to create pthread.\n");

exit(-1);

}

printf("This is the main thread.\n");

pthread_join(tid, NULL); //等待新线程结束,防止主线程退出

return 0;

}

```

上面的代码中,我们首先定义了一个新的线程函数thread_func,它的返回值是void*,参数是void*。在主函数中,我们通过pthread_create函数创建了一个新线程,并传入了线程函数thread_func。该函数的返回值为0时说明成功创建了线程,如果返回值不为0,则说明失败。接下来,我们向这个新线程传了一个void类型的参数NULL,最后通过pthread_join函数等待新线程结束。

二、创建多个线程

在Linux环境下,我们可以同时创建多个线程来提高程序的运行效率。下面是一个创建多个线程的例子:

```c

#include

#include

#include

void *thread_func(void *arg)

{

int *p = (int*)arg;

printf("This is a new thread, arg: %d\n", *p);

pthread_exit(NULL);

}

int main()

{

pthread_t tid[3];//创建3个线程

int i;

int arg[3] = {1, 2, 3};//传递给线程函数的参数

int ret;

for(i=0;i<3;i++){

ret = pthread_create(&tid[i], NULL, thread_func, &arg[i]);

if (ret != 0) {

printf("Fail to create pthread.\n");

exit(-1);

}

printf("This is the %dth main thread.\n", i+1);

}

for(i=0;i<3;i++){

pthread_join(tid[i], NULL);//等待新线程结束,防止主线程退出

}

return 0;

}

```

上面的代码中,我们通过定义一个数组来存放多个线程的标识符tid和传递给线程函数的参数arg,然后通过for循环来创建多个线程。接下来,我们通过pthread_join函数等待新线程结束。

三、线程的互斥和同步

在Linux中,多个线程同时访问共享资源时,可能会出现数据不一致的问题。为了解决这个问题,我们可以使用锁(mutex),它可以保证在某个线程访问资源时,其他线程不能访问这个资源,直到该线程结束对资源的访问。

下面是一个使用互斥锁的例子:

```c

#include

#include

#include

pthread_mutex_t mutex;//定义互斥锁

int counter = 0;//定义共享全局变量

void *thread_func(void *arg)

{

int i;

pthread_mutex_lock(&mutex);//访问资源前先要上锁

for(i=0;i<100;i++){

counter++;

}

pthread_mutex_unlock(&mutex);//访问资源后要解锁

printf("This is a new thread, counter: %d\n", counter);

pthread_exit(NULL);

}

int main()

{

pthread_t tid[3];//创建3个线程

int i;

int arg[3] = {1, 2, 3};//传递给线程函数的参数

int ret;

pthread_mutex_init(&mutex, NULL);//初始化互斥锁

for(i=0;i<3;i++){

ret = pthread_create(&tid[i], NULL, thread_func, &arg[i]);

if (ret != 0) {

printf("Fail to create pthread.\n");

exit(-1);

}

printf("This is the %dth main thread.\n", i+1);

}

for(i=0;i<3;i++){

pthread_join(tid[i], NULL);//等待新线程结束,防止主线程退出

}

pthread_mutex_destroy(&mutex);//销毁互斥锁

printf("Counter value: %d\n", counter);

return 0;

}

```

上面的代码中,我们通过定义一个互斥锁mutex来保护counter这个全局变量,从而避免了多个线程对counter的访问冲突。

扫码咨询 领取资料


软考.png


软件设计师 资料下载
备考资料包大放送!涵盖报考指南、考情深度解析、知识点全面梳理、思维导图等,免费领取,助你备考无忧!
立即下载
软件设计师 历年真题
汇聚经典真题,展现考试脉络。精准覆盖考点,助您深入备考。细致解析,助您查漏补缺。
立即做题

软考资格查询系统

扫一扫,自助查询报考条件