Linux创建两个线程,实现两个线程轮流数数的功能。
时间: 2024-03-10 10:50:06 浏览: 28
好的,我来为您解答。
在Linux中创建线程需要使用pthread库,下面是实现两个线程轮流数数的示例代码:
```c
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int count = 0;
void *thread1(void *arg)
{
while (1) {
pthread_mutex_lock(&mutex);
while (count % 2 == 1) {
pthread_cond_wait(&cond, &mutex);
}
printf("Thread 1: %d\n", count);
count++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
if (count > 10) {
break;
}
}
return NULL;
}
void *thread2(void *arg)
{
while (1) {
pthread_mutex_lock(&mutex);
while (count % 2 == 0) {
pthread_cond_wait(&cond, &mutex);
}
printf("Thread 2: %d\n", count);
count++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
if (count > 10) {
break;
}
}
return NULL;
}
int main()
{
pthread_t t1, t2;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&t1, NULL, thread1, NULL);
pthread_create(&t2, NULL, thread2, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
```
在该示例中,我们创建了两个线程t1和t2,它们轮流数数。线程间的同步是通过互斥锁和条件变量实现的。其中,互斥锁用于保护共享变量count的访问,条件变量用于实现线程间的通信。
当count为偶数时,t1线程打印count并将count加1,然后唤醒t2线程;当count为奇数时,t2线程打印count并将count加1,然后唤醒t1线程。当count大于10时,两个线程退出。
希望能解答您的问题。