分类:
2008-10-13 16:51:22
//*********************************************
// Version: 1.0.0
// Author:
// Copyright: copyleft,free
// Purpose: SharedMem
// Date: 2004-9-10
//*********************************************
#include
#include
#include
#include
#include
#include
void* reader_function (void* p);
//void* writer_function ( void* p );
char buffer;
int buffer_has_item=0;
pthread_mutex_t mutex;
//struct timespec delay;
int main ( void )
{
pthread_t reader;
/* 定义延迟时间*/
//delay.tv_sec = 2;
//delay.tv_nec = 0;
/* 用默认属性初始化一个互斥锁对象*/
pthread_mutex_init(&mutex,NULL);
printf("\n开始产生新线程");
pthread_create(&reader, NULL, &reader_function, NULL);
sleep(10);
printf("\n线程产生完毕");
// writer_function();
pthread_mutex_destroy(&mutex);
return 0;
}
/*
void* writer_function (void* p)
{
while(1)
{
// 锁定互斥锁
pthread_mutex_lock (&mutex);
if (buffer_has_item==0)
{
buffer=make_new_item( );
buffer_has_item=1;
}
// open mutex
pthread_mutex_unlock(&mutex);
//pthread_delay_np(&delay);
sleep(1);
}
}
*/
void* reader_function(void* p)
{
printf("\n新线程 step--1");
sleep(1);
printf("\n新产生的线程 step --2\n");
while(1)
{
printf("\n进入锁\n");
pthread_mutex_lock(&mutex);
if(buffer_has_item==1)
{
//consume_item(buffer);
buffer_has_item=0;
}
printf("\n进入解锁\n");
pthread_mutex_unlock(&mutex);
//pthread_delay_np(&delay);
sleep(1);
}
printf("\n离开线程函数-- step3:");
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
makefile文件:
MutexTest:MutexTest.o
g++ -o $@ $^ -lpthread
MutexTest.o:MutexTest.cpp
g++ -c $< -lpthread
clean:
rm MutexTest
rm MutexTest.o