我正在尝试使用 pthread 模拟发送和接收功能。我确实实现了以下代码。但有时它会挂起或产生错误的结果。
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);
}
你认为我在这里错过了什么?
谢谢