Linux多线程的一个小例子

时间:2021-04-02 17:37:56
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h> #define MAX_COUNT 9
pthread_mutex_t mutex; //互斥变量
pthread_cond_t cond; //条件变量
int count = 0; void AddCount_Odd_Func(void);
void AddCount_Even_Func(void); int main()
{
int ret;
pthread_t odd_thread, even_thread; //两个线程
pthread_attr_t thread_attr; //线程的属性结构 count = 0;
pthread_mutex_init(&mutex, NULL); //互斥变量的初始化
pthread_cond_init(&cond, NULL); //条件变量的初始化
ret = pthread_attr_init(&thread_attr); //属性结构体初始化
if (ret != 0)
{
perror("Attribute Creation Failed!");
exit(EXIT_FAILURE);
} pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED); //设置线程分离状态的函数,PTHREAD_CREATE_DETACHED(分离线程):不需要创建线程的线程等待
//函数运行结束线程便终止,同时释放占用的系统资源
ret = pthread_create(&odd_thread, &thread_attr, (void *)&AddCount_Odd_Func, NULL);
if (ret != 0)
{
perror("Thread Creation Failed!");
exit(EXIT_FAILURE);
}
ret = pthread_create(&even_thread, &thread_attr, (void *)&AddCount_Even_Func, NULL);
if (ret != 0)
{
perror("Thread Creation Failed!");
exit(EXIT_FAILURE);
} while (count < MAX_COUNT);
printf("Finished!\n");
pthread_cond_destroy(&cond); //销毁条件变量
pthread_mutex_destroy(&mutex);
return 0;
} void AddCount_Odd_Func(void)
{
pthread_mutex_lock(&mutex);
while (count < MAX_COUNT)
{
if (count % 2 == 1)
{
count++;
printf("AddCount_Odd_Func(): count = %d.\n", count);
pthread_cond_signal(&cond); //用来释放被阻塞在条件变量cond上的线程
}
else
pthread_cond_wait(&cond, &mutex); //使线程阻塞在条件变量cond上
}
pthread_mutex_unlock(&mutex);
} void AddCount_Even_Func(void)
{
pthread_mutex_lock(&mutex);
while (count < MAX_COUNT)
{
if (count % 2 == 0)
{
count++;
printf("AddCount_Even_Func(): count = %d.\n", count);
pthread_cond_signal(&cond);
}
else
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
}

gcc example.c -lpthread

运行结果如下:

Linux多线程的一个小例子