多线程问题
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
pthread_mutex_t mymutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mymutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t mycond = PTHREAD_COND_INITIALIZER;
void *mythread1(void *param)
{
printf("begin mythread1.\n");
pthread_mutex_lock(&mymutex1);
printf("wait in mythread1.\n");
pthread_cond_wait(&mycond,&mymutex1);
pthread_mutex_unlock(&mymutex1);
printf("end mythread1.\n");
return NULL;
}
void *mythread2(void *param)
{
printf("begin mythread2.\n");
pthread_mutex_lock(&mymutex2);
printf("wait in mythread2.\n");
pthread_cond_wait(&mycond,&mymutex2);
pthread_mutex_unlock(&mymutex2);
printf("end mythread2.\n");
return NULL;
}
int main(void)
{
printf("begin main thread.\n");
int i;
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,mythread1,NULL);
pthread_create(&tid2,NULL,mythread2,NULL);
sleep(5);
printf("try to wake up mythread1 and mythread2 in main thread.\n");
if(pthread_cond_broadcast(&mycond)){
printf("error\n");
return 1;
}
void *res;
pthread_join(tid1, &res);
pthread_join(tid2, &res);
printf("end main thread.\n");
return 0;
}
我在机器上运行,只把tid1唤醒了,各位遇到过吗?如何解决
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
pthread_mutex_t mymutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mymutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t mycond = PTHREAD_COND_INITIALIZER;
void *mythread1(void *param)
{
printf("begin mythread1.\n");
pthread_mutex_lock(&mymutex1);
printf("wait in mythread1.\n");
pthread_cond_wait(&mycond,&mymutex1);
pthread_mutex_unlock(&mymutex1);
printf("end mythread1.\n");
return NULL;
}
void *mythread2(void *param)
{
printf("begin mythread2.\n");
pthread_mutex_lock(&mymutex2);
printf("wait in mythread2.\n");
pthread_cond_wait(&mycond,&mymutex2);
pthread_mutex_unlock(&mymutex2);
printf("end mythread2.\n");
return NULL;
}
int main(void)
{
printf("begin main thread.\n");
int i;
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,mythread1,NULL);
pthread_create(&tid2,NULL,mythread2,NULL);
sleep(5);
printf("try to wake up mythread1 and mythread2 in main thread.\n");
if(pthread_cond_broadcast(&mycond)){
printf("error\n");
return 1;
}
void *res;
pthread_join(tid1, &res);
pthread_join(tid2, &res);
printf("end main thread.\n");
return 0;
}
我在机器上运行,只把tid1唤醒了,各位遇到过吗?如何解决
...全文
相关推荐
DateFormat多线程问题
NULL 博文链接:https://zhaoshunxin.iteye.com/blog/1291905
浅析Python多线程下的变量问题
主要介绍了Python多线程下的变量问题,由于GIL的存在,Python的多线程编程问题一直是开发者中的热点话题,需要的朋友可以参考下
多线程死锁问题
死锁问题,java多线程死锁
Python tkinter 多线程 哲学家进餐问题
Python tkinter 多线程 哲学家进餐问题 网上找了好久都没有自己满意的代码,于是自己学了一个,不过这只是个雏形,要想变成你满意的程序,需要靓男靓女们自己的努力啦! 废话不多说,直接上代码! from tkinter import * from PIL import Image,ImageTk import threading from time import sleep import os, random """首先导入必要的模块,由于涉及到导入非gif的图片文件,就要用到PIL库""" """接下来开始写哲学家这个类""" class Philosopher(threading.
个人总结40个Java多线程面试问题和答案
个人总结40个Java多线程面试问题和答案,很全面,让你不再担心多线程的面试问题。


