【发布时间】:2020-04-29 17:02:37
【问题描述】:
我正在学习多线程并尝试创建一个可以交替打印两个字符串的程序。 我写了以下代码:
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_mutex_t lock;
void print(char a[50]){
pthread_mutex_lock(&lock);
printf("%s", a); //output console is the shared resource
sleep(2);
pthread_mutex_unlock(&lock);
}
void* hello(void* status){
while(*((char*)status) != '\n'){
print("Hello World\n");
}
}
void* bye(void* status){
while(*((char*)status) != '\n'){
print("Goodbye World\n");
}
}
int main(){
pthread_t id1, id2;
char status = '\0';
int state;
if (pthread_mutex_init(&lock, NULL) != 0) {
printf("\n mutex init has failed\n");
exit(1);
}
printf("Starting Threads (Press Enter to terminate)\n");
state = pthread_create(&id1, NULL, hello, &status);
if(state != 0){
printf("Could not create thread, exiting.\n");
exit(1);
}
state = pthread_create(&id2, NULL, bye, &status);
if(state != 0){
printf("Could not create thread, exiting.\n");
exit(1);
}
scanf("%c", &status);
printf("Out of The Threads\n");
pthread_mutex_destroy(&lock);
return 0;
}
据我了解,互斥锁应该为 hello 函数锁定 print 函数一次,然后为 bye 函数锁定一次。但我只得到这个输出:
Starting Threads (Press Enter to terminate)
Hello World
Hello World
Hello World
Hello World
Hello World
为什么只有 hello 函数被分配了 print 函数?我如何让它同时打印?
【问题讨论】:
标签: c multithreading mutex thread-synchronization