linux编程thread6.c,创建3个线程。假如三个线程的ID分别为A,B,C。每个线程把自己的ID在屏幕上打印10遍,要求输出结果必须按照ABC的顺序显示,例如ABCABC…..。
时间: 2024-03-02 16:51:12 浏览: 20
下面是一个示例代码,可以实现创建三个线程,分别打印自己的ID,要求按照ABC顺序显示:
```c
#include <stdio.h>
#include <pthread.h>
#define THREAD_NUM 3
pthread_mutex_t mutex;
pthread_cond_t cond_var[THREAD_NUM];
void *print_func(void *arg) {
int id = *(int *)arg;
int i;
for (i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
while (id != 0 && pthread_cond_wait(&cond_var[id], &mutex) != 0);
printf("%c", 'A' + id);
if (id == THREAD_NUM - 1) {
printf("\n");
pthread_cond_broadcast(&cond_var[0]);
} else {
pthread_cond_signal(&cond_var[id+1]);
}
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t threads[THREAD_NUM];
int ids[THREAD_NUM] = {0, 1, 2};
int i;
pthread_mutex_init(&mutex, NULL);
for (i = 0; i < THREAD_NUM; i++) {
pthread_cond_init(&cond_var[i], NULL);
}
for (i = 0; i < THREAD_NUM; i++) {
pthread_create(&threads[i], NULL, print_func, &ids[i]);
}
for (i = 0; i < THREAD_NUM; i++) {
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&mutex);
for (i = 0; i < THREAD_NUM; i++) {
pthread_cond_destroy(&cond_var[i]);
}
return 0;
}
```
在这个示例代码中,我们创建了三个线程,每个线程打印自己的ID,要求按照ABC的顺序显示。为了满足要求,我们使用了一个互斥锁和三个条件变量。每个线程通过互斥锁来保证自己的输出不会被其他线程打断,通过条件变量来实现线程间的同步。
具体来说,线程A首先获取互斥锁,打印自己的ID,并发出一个信号通知线程B继续执行。线程B收到信号后获取互斥锁,打印自己的ID,并通知线程C继续执行。线程C收到信号后获取互斥锁,打印自己的ID,并通知线程A继续执行。这样循环往复,就可以实现按照ABC顺序显示的效果。
需要注意的是,为了避免线程在等待条件变量时被信号中断而导致的竞争条件,我们使用了while循环来等待条件变量,并在等待过程中持有互斥锁。同时,为了避免线程A在最后一次输出后阻塞,我们使用了pthread_cond_broadcast()函数来广播信号,让所有等待的线程都能继续执行。