linux利用互斥锁,开启 3 个线程,每个线程将自己的线程号 在屏幕上打印 5 遍,要求输出结果必须按线程 1 线程 2 线程 3 的顺序显示;如:线程 1 线程 2 线程 3 线程 1 线程 2 线程 3 线程 1 线程 2 线程 3 线程 1 线程 2 线程 3 线程 1 线程 2 线程 3
时间: 2023-07-16 09:16:31 浏览: 48
以下是一个简单的实现,使用互斥锁和条件变量确保三个线程按照指定顺序交替打印线程号:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define THREAD_NUM 3
#define PRINT_COUNT 5
pthread_mutex_t mutex;
pthread_cond_t condition_var;
int current_thread = 1;
void* print_thread_number(void* arg) {
int thread_num = *(int*)arg;
for (int i = 0; i < PRINT_COUNT; ++i) {
pthread_mutex_lock(&mutex);
while (current_thread != thread_num) {
pthread_cond_wait(&condition_var, &mutex);
}
printf("线程 %d\n", thread_num);
current_thread = (current_thread % THREAD_NUM) + 1;
pthread_cond_broadcast(&condition_var);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t threads[THREAD_NUM];
int thread_args[THREAD_NUM];
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&condition_var, NULL);
for (int i = 0; i < THREAD_NUM; ++i) {
thread_args[i] = i + 1;
pthread_create(&threads[i], NULL, print_thread_number, &thread_args[i]);
}
for (int i = 0; i < THREAD_NUM; ++i) {
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&condition_var);
return 0;
}
```
运行结果:
```
线程 1
线程 2
线程 3
线程 1
线程 2
线程 3
线程 1
线程 2
线程 3
线程 1
线程 2
线程 3
线程 1
线程 2
线程 3
```
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)