啊....同步终于搞清了, 晕死了....
这东西真让我难解, 太笨了...可惜没有一本书来看, 时间太急.....
两个线程同步 加锁
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <semaphore.h>
#define BUFSIZE 4
#define NUMBER 8
int sum_of_number=0;
int value=0; //全局变量, 要注意加锁
/*定义两个变量 信号量*/
sem_t write_res_number;
sem_t read_res_number;
/* 初始化锁 ¯*/
pthread_mutex_t buffer_mutex=PTHREAD_MUTEX_INITIALIZER;
static void *producer(void * arg)
{
int i;
for(i=0;i<=12;i++)
{
/* 减少可写的资源数*/
sem_wait(&write_res_number);
/* 加锁 */
pthread_mutex_lock(&buffer_mutex);
value+=1;
printf("procuder write: %d\n",value);
/* 解锁 */
pthread_mutex_unlock(&buffer_mutex);
sem_post(&read_res_number);
}
return NULL;
}
static void * consumer(void * arg)
{
int i,num;
for(i=0;i<=12;i++)
{
sem_post(&write_res_number);
sem_wait(&read_res_number);
pthread_mutex_lock(&buffer_mutex);
value+=1;
printf("read value %d.\n",value);
pthread_mutex_unlock(&buffer_mutex);
}
return NULL;
}
int main(int argc,char ** argv)
{
pthread_t p_tid;
pthread_t c_tid;
sem_init(&write_res_number,0,0);
sem_init(&read_res_number,0,0);
pthread_create(&p_tid,NULL,producer,NULL);
pthread_create(&c_tid,NULL,consumer,NULL);
pthread_join(p_tid,NULL);
pthread_join(c_tid,NULL);
pthread_mutex_destroy(&buffer_mutex); /*Êջػ¥³âÁ¿×ÊÔ´*/
}
在linux 下一样.
我在cygwin 运行结果:
$ gcc -lpthread -o th th
$ ./th
procuder write: 1
read value 2.
procuder write: 3
read value 4.
procuder write: 5
read value 6.
procuder write: 7
read value 8.
procuder write: 9
read value 10.
procuder write: 11
read value 12.
procuder write: 13
read value 14.
procuder write: 15
read value 16.
procuder write: 17
read value 18.
procuder write: 19
read value 20.
procuder write: 21
read value 22.
procuder write: 23
read value 24.
procuder write: 25
read value 26.
$