linux创建两个线程实现交替计数
时间: 2023-08-24 09:03:55 浏览: 49
好的,我可以为您提供一个 Linux 平台下使用 pthread 库实现的示例代码。
```c
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int count = 0;
void *thread1(void *arg) {
for (int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
count++;
printf("Thread1: %d\n", count);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void *thread2(void *arg) {
for (int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
while (count % 2 == 0) {
pthread_cond_wait(&cond, &mutex);
}
count++;
printf("Thread2: %d\n", count);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t t1, t2;
pthread_create(&t1, NULL, thread1, NULL);
pthread_create(&t2, NULL, thread2, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
```
这个示例使用了 pthread 库来创建了两个线程 `t1` 和 `t2`,这两个线程都共享一个计数器 `count`,并且在各自的循环里通过互斥锁 `mutex` 和条件变量 `cond` 来实现交替计数。其中,线程 `t1` 每次增加计数器的值并发出信号通知线程 `t2`,而线程 `t2` 则等待信号并在收到信号后增加计数器的值并再次发出信号通知线程 `t1`。最后,调用 `pthread_join()` 函数等待两个线程执行完毕。