第一关
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//全局互斥锁变量
extern pthread_mutex_t mutex;
//全局共享变量
extern char *buffer[3];
extern int position;
/************************
* 参数arg: 是线程函数的参数
*************************/
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);
}
第二关
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//全局自旋锁变量
extern pthread_spinlock_t lock;
//全局共享变量
extern char *buffer[3];
extern int position;
/************************
* 参数arg: 是线程函数的参数
*************************/
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);
}
第三关
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//全局互斥锁变量和条件变量
extern pthread_mutex_t mutex;
extern pthread_cond_t cond;
//全局共享变量
extern char *buffer[3];
extern int position;
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
/************************
* 参数arg: 是线程函数的参数
*************************/
void *ThreadHandler1(void *arg)
{
int i;
for(i = 0; i < 3; i++)
{
usleep(500);
position++;
//通知ThreadHandler2函数执行赋值操作
/********** BEGIN **********/
pthread_cond_signal(&has_product);
/********** END **********/
}
pthread_exit(NULL);
}
/************************
* 参数arg: 是线程函数的参数
*************************/
void *ThreadHandler2(void *arg)
{
/********** BEGIN **********/
pthread_mutex_lock(&mutex);
pthread_cond_wait(&has_product, &mutex);
/********** END **********/
buffer[position] = (char *)arg;
/********** BEGIN **********/
pthread_mutex_unlock(&mutex);
/********** END **********/
pthread_exit(NULL);
}
第四关
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
struct Data
{
int number; //存放生产的数据
struct Data *next;
};
//定义数据区头和尾
extern struct Data *beginData;
const int max_number = 10; //生产者与消费者的最大生产和消费任务
int consumer_number = 0; //消费者已经消费的任务数
//全局互斥锁变量和条件变量
extern pthread_mutex_t mutex;
extern pthread_cond_t cond;
/************************
* 参数arg: 是线程函数的参数
*************************/
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);
consumer_number++;
//将消费后的数据释放掉
struct msg *tmp = beginData;
beginData = beginData->next;
free(tmp);
pthread_mutex_unlock(&mutex);
/********** END **********/
}
pthread_exit(NULL);
}