在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的访问冲突。
扫码咨询 领取资料