以互斥量方式,实现 2 个线程每隔一秒互斥输出 1-10 数字,程序命名为 mutex.c
时间: 2023-06-09 08:05:21 浏览: 45
好的,我理解你的要求。下面是实现这个功能的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int count = 1;
void *func1(void *arg) {
while (1) {
pthread_mutex_lock(&mutex);
if (count > 10) {
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
if (count % 2 == 1) {
printf("Thread1: %d\n", count++);
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
usleep(1000000); // 1秒
}
}
void *func2(void *arg) {
while (1) {
pthread_mutex_lock(&mutex);
if (count > 10) {
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
if (count % 2 == 0) {
printf("Thread2: %d\n", count++);
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
usleep(1000000); // 1秒
}
}
int main() {
pthread_t thread1, thread2;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&thread1, NULL, func1, NULL);
pthread_create(&thread2, NULL, func2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
```
这个程序创建了两个线程,分别执行 `func1` 和 `func2` 函数。这两个函数是互斥的,即每次只有一个线程可以执行输出操作。通过 `pthread_mutex_lock` 和 `pthread_mutex_unlock` 来实现互斥,通过 `pthread_cond_wait` 和 `pthread_cond_signal` 来实现线程间的同步。每个线程在输出完自己的数后通过 `pthread_cond_signal` 唤醒另一个线程,然后等待另一个线程输出完它的数后再继续执行。这样就可以实现每隔一秒输出一次交替的数字 1-10。