【发布时间】:2021-12-28 11:22:10
【问题描述】:
我刚开始学习线程、互斥体和条件变量,我有以下代码:
#include <pthread.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mutex;
static pthread_mutexattr_t attr;
volatile int x = 0;
void *thread_one_function (void *dummy) {
printf("In func one.");
while (true) {
pthread_mutex_lock (&mutex);
x = rand ();
pthread_cond_signal (&cond);
pthread_mutex_unlock (&mutex);
}
}
void *thread_two_function (void *dummy) {
printf("In func two.");
pthread_mutex_lock (&mutex);
while (x != 10) {
pthread_cond_wait (&cond, &mutex);
}
printf ("%d\n", x);
pthread_mutex_unlock (&mutex);
printf ("%d\n", x);
}
int main (void){
pthread_mutexattr_init (&attr);
pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init (&mutex, &attr);
pthread_t one, two;
pthread_create(&one,NULL,thread_one_function,NULL);
pthread_create(&two,NULL,thread_two_function,NULL);
//pthread_join(one,NULL); //with this program will not end.
//pthread_join(two,NULL);
return 0;
}
我编译为gcc prog.c -lpthread -o a.exe
而且我没有得到任何输出。甚至我的线程都没有进入这两个功能...... 我究竟做错了什么 ?我的代码是作为多个文档的组合创建的。 感谢您的帮助。
【问题讨论】:
-
改用
rand % 100。 -
不要使用
-lpthread,它只链接libpthread。而是在编译和链接时都使用-pthread,这不仅会导致链接所有需要的附加库,还会影响代码生成。
标签: c pthreads locking mutex condition-variable