第1关:互斥锁
void *ThreadHandler(void *arg)
{
/********** BEGIN **********/
pthread_mutex_lock(&mutex);
/********** END **********/
buffer[position] = (char *)arg;
sleep(1);
position++;
/********** BEGIN **********/
pthread_mutex_unlock(&mutex);
/********** END **********/
pthread_exit(NULL);
}
第2关:自旋锁
void *ThreadHandler(void *arg)
{
/********** BEGIN **********/
pthread_spin_lock(&lock);
/********** END **********/
buffer[position] = (char *)arg;
sleep(1);
position++;
/********** BEGIN **********/
pthread_spin_unlock(&lock);
/********** END **********/
pthread_exit(NULL);
}
第3关:条件变量
void *ThreadHandler1(void *arg)
{
int i;
for(i = 0; i < 3; i++)
{
usleep(500);
position++;
//通知ThreadHandler2函数执行赋值操作
/********** BEGIN **********/
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
/********** END **********/
}
pthread_exit(NULL);
}
/************************
* 参数arg: 是线程函数的参数
*************************/
void *ThreadHandler2(void *arg)
{
/********** BEGIN **********/
pthread_mutex_lock(&mutex);
while (position == 0)
{
pthread_cond_wait(&cond, &mutex);
}
/********** END **********/
buffer[position] = (char *)arg;
/********** BEGIN **********/
pthread_mutex_unlock(&mutex);
/********** END **********/
pthread_exit(NULL);
}
第4关:项目实战
void *Consumer(void *arg)
{
while(1)
{
/********** BEGIN **********/
pthread_mutex_lock(&mutex);
while(beginData==NULL)
{
pthread_cond_wait(&cond,&mutex);
}
if (beginData->number == -1)
{
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
printf("%d\n", beginData->number);
struct Data *tmp = beginData;
beginData = beginData->next;
free(tmp);
pthread_mutex_unlock(&mutex);
/********** END **********/
}
pthread_exit(NULL);
}