用linux编程创建两个线程,实现两个线程轮流数数的功能
时间: 2023-12-10 14:37:55 浏览: 32
以下是用 C 语言在 Linux 系统下创建两个线程,实现轮流数数的示例代码:
```c
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex; // 互斥锁
pthread_cond_t cond; // 条件变量
int num = 0; // 全局计数器
void *thread1(void *arg)
{
while (1)
{
pthread_mutex_lock(&mutex); // 加锁
while (num % 2 == 0) // 当前轮到线程 1 数数
{
printf("Thread 1: %d\n", num);
num++;
pthread_cond_signal(&cond); // 唤醒等待该条件变量的线程
}
pthread_mutex_unlock(&mutex); // 解锁
}
}
void *thread2(void *arg)
{
while (1)
{
pthread_mutex_lock(&mutex); // 加锁
while (num % 2 == 1) // 当前轮到线程 2 数数
{
printf("Thread 2: %d\n", num);
num++;
pthread_cond_signal(&cond); // 唤醒等待该条件变量的线程
}
pthread_cond_wait(&cond, &mutex); // 等待该条件变量的信号
pthread_mutex_unlock(&mutex); // 解锁
}
}
int main()
{
pthread_t tid1, tid2;
pthread_mutex_init(&mutex, NULL); // 初始化互斥锁
pthread_cond_init(&cond, NULL); // 初始化条件变量
pthread_create(&tid1, NULL, thread1, NULL); // 创建线程 1
pthread_create(&tid2, NULL, thread2, NULL); // 创建线程 2
pthread_join(tid1, NULL); // 等待线程 1 结束
pthread_join(tid2, NULL); // 等待线程 2 结束
pthread_mutex_destroy(&mutex); // 销毁互斥锁
pthread_cond_destroy(&cond); // 销毁条件变量
return 0;
}
```
线程 1 和线程 2 都会一直循环,每次判断计数器 num 的奇偶性来决定是否轮到自己数数。当轮到自己数数时,会先输出当前的计数器 num,然后将计数器加一,并且唤醒等待该条件变量的线程。如果没有轮到自己数数,则会等待条件变量的信号,直到被唤醒。
在主函数中,我们调用了 pthread_create 函数来创建两个线程,分别执行 thread1 和 thread2 函数。然后使用 pthread_join 函数来等待两个线程结束。最后,我们销毁了互斥锁和条件变量。