我有一个简单的 C 程序,它使用互斥体从一个线程的标准输入中收集一个字符,然后在另一个线程上打印出来。两个线程都正确启动(下面的 printf 表示线程开始运行),但是自从我引入 Mutex' 以来,这两个线程都没有运行。有谁知道为什么?(我在我的 char 数组中收集了两个字符,因为我也在收集返回字符。)
谢谢!
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
struct thread_info { /* Used as argument to thread_start() */
pthread_t thread_id;/* ID returned by pthread_create() */
char passedChar[2];
pthread_mutex_t passedCharMutex;
pthread_cond_t conditionalSignal;
};
static void *thread_1_start(void *arg) {
struct thread_info *myInfo = arg;
printf("Started thread id: %d\n", myInfo->thread_id);
while (1) {
printf("thread1 while ran");
pthread_mutex_lock(&myInfo->passedCharMutex);
int rid = read(0,myInfo->passedChar,2);
pthread_mutex_unlock(&myInfo->passedCharMutex);
}
pthread_exit(0);
}
int main() {
struct thread_info tinfo;
printf("Main thread id: %d\n", tinfo.thread_id);
int s = pthread_create(&tinfo.thread_id,
NULL, // was address of attr, error as this was not initialised.
&thread_1_start,
&tinfo);
pthread_join(tinfo.thread_id,NULL);
while (1) {
printf("thread2 while ran");
pthread_mutex_lock(&tinfo.passedCharMutex);
write(1,tinfo.passedChar,2);
pthread_mutex_unlock(&tinfo.passedCharMutex);
}
}