【发布时间】:2017-11-03 20:33:57
【问题描述】:
我正在尝试学习如何在 C 中正确使用条件变量。 作为我自己的练习,我正在尝试制作一个带有 2 个线程的小程序,这些线程在无限循环中打印“Ping”,然后是“Pong”。
我写了一个小程序:
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* T1(){
printf("thread 1 started\n");
while(1)
{
pthread_mutex_lock(&lock);
sleep(0.5);
printf("ping\n");
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
pthread_cond_wait(&cond,&lock);
}
}
void* T2(){
printf("thread 2 started\n");
while(1)
{
pthread_cond_wait(&cond,&lock);
pthread_mutex_lock(&lock);
sleep(0.5);
printf("pong\n");
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
}
int main(void)
{
int i = 1;
pthread_t t1;
pthread_t t2;
printf("main\n");
pthread_create(&t1,NULL,&T1,NULL);
pthread_create(&t2,NULL,&T2,NULL);
while(1){
sleep(1);
i++;
}
return EXIT_SUCCESS;
}
当运行这个程序时,我得到的输出是:
main
thread 1 started
thread 2 started
ping
知道程序没有按预期执行的原因是什么吗?
提前致谢。
【问题讨论】:
-
sleep是一个非标准函数,但我认为sleep(0.5)实际上是sleep(0),因为它通常需要一个整数类型作为参数。 -
@Bathsheba
sleep与 pthread 一样标准。假设您在具有 pthread 的系统上拥有它是非常安全的(并且它需要一个无符号作为参数)。
标签: c multithreading concurrency