我正在尝试使用pthreads模拟发送和接收功能。我确实实现了以下代码。但有时它会挂起或产生错误的结果。
int g_sender,g_receiver; //global variables to keep track of the sender and receiver
void send(double ** data,int sender,int receiver, int size[],int block_size){
int i;
pthread_mutex_lock(&lock);
for (i=0;i<size[0];i++)
memcpy(sharedA[i],data[i],size[1]*block_size);
g_sender = sender;
g_receiver = receiver;
sem_wait(&sem);
pthread_mutex_unlock(&lock);
}
void receive(double ** data, int sender,int receiver, int size[],int block_size){
int i;
while(!(sender==g_sender && receiver==g_receiver));
for(i=0;i<size[0];i++)
memcpy(data[i],sharedA[i],size[1]*block_size);
g_sender =-1;
g_receiver = -1;
sem_post(&sem);
}
你觉得我在这里错过了什么?
由于
答案 0 :(得分:0)
很多:)
sem_
功能是可中断的,您必须检查是否有
中断发生在sem_wait
sem_t
。请改用互斥锁和条件变量。他们更高
级别接口更适合应用程序代码。