【发布时间】:2019-11-18 11:53:06
【问题描述】:
如何使用 lock_mutex 或 sleep 函数强制三个线程再次打印“hello world”?我已经完成了...
/* t2.c
synchronize threads through mutex and conditional variable
To compile use: gcc -o t2 t2.c -lpthread
*/
#include <stdio.h>
#include <pthread.h>
void hello(); // define three routines called by threads
void world();
void again(); /*new statment*/
/* global variable shared by threads */
pthread_mutex_t mutex; // mutex
pthread_cond_t done_hello; // conditional variable
int done = 0; // testing variable
int main(int argc, char* argv[])
{
pthread_t tid_hello, // thread id
tid_world, tid_again;
/* initialization on mutex and cond variable */
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&done_hello, NULL);
pthread_create(&tid_hello, NULL, (void*)&hello, NULL); //thread creation
pthread_create(&tid_world, NULL, (void*)&world, NULL); //thread creation
pthread_create(&tid_again, NULL, (void*)&again, NULL); //thread creation/*new statment*/
/* main waits for the three threads to finish by order */
pthread_join(tid_hello, NULL);
pthread_join(tid_world, NULL);
pthread_join(tid_again, NULL); /*new statment*/
printf("\n");
return 0;
}
void hello()
{
pthread_mutex_lock(&mutex);
printf(" hello");
fflush(stdout); // flush buffer to allow instant print out
done = 2;
pthread_cond_signal(&done_hello); // signal world() thread
pthread_mutex_unlock(&mutex); // unlocks mutex to allow world to print
return;
}
void world()
{
pthread_mutex_lock(&mutex);
/* world thread waits until done == 1. */
while (done == 1)
pthread_cond_wait(&done_hello, &mutex);
printf(" world");
fflush(stdout);
pthread_mutex_unlock(&mutex); // unlocks mutex
return;
}
void again() /*new function*/
{
pthread_mutex_lock(&mutex);
/* again thread waits until done == 0. */
while (done == 0)
pthread_cond_wait(&done_hello, &mutex);
printf(" again");
fflush(stdout);
pthread_mutex_unlock(&mutex); // unlocks mutex
return;
}
【问题讨论】:
-
不要将函数指针转换为
void *,只需使用正确的原型void *hello(void *) -
当我使用你的原型时,会发生这个错误 t2.c:31:37: error: expected expression pthread_create (&tid_hello, NULL, void *hello(void *)
-
pthread_create调用应如下所示:pthread_create(&tid_hello, NULL, hello, NULL);和函数void *hello(void *) { pthread_mutex_lock(&mutex); ... }。