#include
#include
#include
#include
#include
#include
#define THREAD_NUM 25
typedef struct
{undefined
FILE *_fp
int _nThreadId//第几个线程
sem_t *_semLock
}IDD_THREAD_PARAM
void *ThreadFunc(void *args)
{undefined
char sLine[100+1]
FILE *fpRead = ((IDD_THREAD_PARAM *)args)->_fp
sem_t *semLock = ((IDD_THREAD_PARAM *)args)->_semLock
int nId = ((IDD_THREAD_PARAM *)args)->_nThreadId
sem_wait(semLock)
while(!feof(fpRead))
{undefined
memset(sLine,0,sizeof(sLine))
fgets(sLine,100,fpRead)
fprintf(stderr,"Thread ID-%d:%s",nId,sLine)
}
sem_post(semLock)
}
int main()
{undefined
pthread_t *pThreads
sem_t semLock
pThreads = (pthread_t *)malloc(THREAD_NUM*sizeof(pthread_t))
sem_init(&semLock,0,1)
FILE *fp = fopen("test.txt","r")
//开始线程循环
IDD_THREAD_PARAM param
for(int i=0i
{undefined
memset(param,0,sizeof(IDD_THREAD_PARAM))
param._fp = fp
param._nThreadId = i
param._semLock = &semLock
pthread_create((pThreads+i),NULL,ThreadFunc,param)
}
for(int i=0i
pthread_join(*(pThreads+i),NULL)
free(pThreads)
pThreads = NULL
fclose(fp)
fp = NULL
return 0
}
实现一个队列CQueue CQueue提供两个公有成员函数 addTail():往队列尾部增加一个元素 removeHead():读出并移除队列的第一个元素 生产者:两个线程通过调用CQueue::addTail()往队列中增加元素 消费者:一个线程通过调用CQueue::removeHead()从队列中读取元素 #include <iostream> #include <list> #include <windows.h> #include <process.h> using namespace std #define P(sem) WaitForSingleObject(sem,INFINITE) #define V(sem) ReleaseSemaphore(sem,1,NULL) class CQueue { public: void addTail()//往队列尾部增加一个元素 void removeHead()//读出并移除队列的第一个元素 private: list<int>L } CQueue buffer//全局的缓冲区 const int buf_size = 10//缓冲区大小 static int GOODS_ID = 0//商品序号 const int producers = 3//生产者数量 const int consumers = 8//消费者数量 void ProducerThread(void* param) void ConsumerThread(void* param) HANDLE empty,occupy,op_mutex int main() { int i int p_id[producers],c_id[consumers]欢迎分享,转载请注明来源:夏雨云
评论列表(0条)