goroutine交替打印1
以下是使用 POSIX 线程库实现的 Linux 双线程交替打印奇偶数的示例代码:
```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 *print_even(void *arg) {
while (count <= 10) {
pthread_mutex_lock(&mutex); // 加锁
if (count % 2 == 0) { // 判断是否为偶数
printf("even thread: %d\n", count);
count++;
pthread_cond_signal(&cond); // 发送信号
} else {
pthread_cond_wait(&cond, &mutex); // 等待信号
}
pthread_mutex_unlock(&mutex); // 解锁
}
pthread_exit(NULL);
}
void *print_odd(void *arg) {
while (count <= 10) {
pthread_mutex_lock(&mutex); // 加锁
if (count % 2 == 1) { // 判断是否为奇数
printf("odd thread: %d\n", count);
count++;
pthread_cond_signal(&cond); // 发送信号
} else {
pthread_cond_wait(&cond, &mutex); // 等待信号
}
pthread_mutex_unlock(&mutex); // 解锁
}
pthread_exit(NULL);
}
int main() {
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, print_even, NULL); // 创建偶数线程
pthread_create(&tid2, NULL, print_odd, NULL); // 创建奇数线程
pthread_join(tid1, NULL); // 等待线程结束
pthread_join(tid2, NULL);
pthread_mutex_destroy(&mutex); // 销毁互斥锁
pthread_cond_destroy(&cond); // 销毁条件变量
return 0;
}
```
上述代码中,我们使用了互斥锁和条件变量来实现线程间的同步和通信。其中,互斥锁用来保护打印计数器 `count` 的访问,条件变量用来等待和发送信号。在偶数线程中,如果当前的 `count` 为偶数,则打印并将 `count` 加 1,并发送信号通知奇数线程;否则等待奇数线程发送信号。在奇数线程中,如果当前的 `count` 为奇数,则打印并将 `count` 加 1,并发送信号通知偶数线程;否则等待偶数线程发送信号。最后,我们使用 `pthread_join` 函数等待两个线程结束,并销毁互斥锁和条件变量。