以互斥量方式,实现 2 个线程互斥输出 1-10 数字,程序命名为 mutex.c
时间: 2023-06-08 15:08:59 浏览: 54
好的,我能够回答你的问题。下面是一个简单的互斥量程序,可以实现两个线程交替打印数字1到10:
```c
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int count = 1;
void *thread_func(void *arg) {
for (int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
while (count % 2 == 0) {
pthread_cond_wait(&cond, &mutex);
}
printf("%d\n", count);
count++;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t thread;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&thread, NULL, thread_func, NULL);
for (int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
while (count % 2 == 1) {
pthread_cond_wait(&cond, &mutex);
}
printf("%d\n", count);
count++;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
pthread_join(thread, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
```
这个程序中,使用了互斥量来实现两个线程的同步。一个线程(thread_func)打印奇数,另一个线程打印偶数,它们交替执行,确保输出1到10的所有数字。pthread_mutex_lock 和 pthread_mutex_unlock 函数用来上锁和解锁互斥量,pthread_cond_wait 函数等待主线程通知并控制条件变量,而 pthread_cond_signal 函数通知线程去执行。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)