Visual C++中的多线程

来源:互联网 发布:计价软件有哪些 编辑:程序博客网 时间:2024/05/26 02:51
 
在C++里面创建和终止线程的函数为:_beginthread和_endthread两个函数,当然,也可以用CreateThread和ExitThread。具体的使用方式可以查看msdn。

那么,怎么样实现加锁与同步呢?可以使用createMutex函数以及createEvent方法等来实现,具体可以参考下例:

#include < iostream>
#include
< windows.h>

using namespace std;
#define BUFSIZE 5
int SharedBuffer[BUFSIZE];
int head,tail;
int count;
HANDLE hMutex;
HANDLE hNotFullEvent, hNotEmptyEvent;
void BB_Producer()
...{
int i;
for (i=20; i>=0; i--) ...{
while(1) ...{
WaitForSingleObject(hMutex,INFINITE);
if (count == BUFSIZE) ...{ // 缓冲区满
ReleaseMutex(hMutex);
// 等待直到缓冲区非满
WaitForSingleObject(hNotFullEvent,INFINITE);
continue;
}

// 得到互斥锁且缓冲区非满,跳出while循环
break;
}

// 得到互斥锁且缓冲区非满,开始产生新数据
cout << "Produce: " << i << endl;
SharedBuffer[tail]
= i;
tail
= (tail+1) % BUFSIZE;
count
++;
ReleaseMutex(hMutex);
// 结束临界区
PulseEvent(hNotEmptyEvent); // 唤醒消费者线程
}

}

void BB_Consumer()
...{
int result;
while (1) ...{
WaitForSingleObject(hMutex,INFINITE);
if (count == 0) ...{ // 没有可以处理的数据
ReleaseMutex(hMutex); // 释放互斥锁且等待
// 等待直到缓冲区非空
WaitForSingleObject(hNotEmptyEvent,INFINITE);
}

else if (SharedBuffer[head] == 0) ...{
cout
<< "Consumed 0: end of data" << endl;
ReleaseMutex(hMutex);
// 结束临界区
ExitThread(0);
}

else ...{ // 获得互斥锁且缓冲区有数据,开始处理
result = SharedBuffer[head];
cout
<< "Consumed: " << result << endl;
head
= (head+1) % BUFSIZE;
count
--;
ReleaseMutex(hMutex);
// 结束临界区
PulseEvent(hNotFullEvent); // 唤醒生产者线程
}

}

}

void main()
...{
HANDLE hThreadVector[
2];
DWORD ThreadID;
count
= 0;
head
= 0;
tail
= 0;
hMutex
= CreateMutex(NULL,FALSE,NULL);
hNotFullEvent
= CreateEvent(NULL,TRUE,FALSE,NULL);
hNotEmptyEvent
= CreateEvent(NULL,TRUE,FALSE,NULL);
hThreadVector[
0] = CreateThread (NULL, 0,
(LPTHREAD_START_ROUTINE) BB_Producer,
NULL,
0, (LPDWORD)&ThreadID);
hThreadVector[
1] = CreateThread (NULL, 0,
(LPTHREAD_START_ROUTINE) BB_Consumer,
NULL,
0, (LPDWORD)&ThreadID);
WaitForMultipleObjects(
2,hThreadVector,TRUE,INFINITE);
}

这是一个典型的生产者-消费者问题,它们公用的资源是SharedBuffer,当Buffer中有数据且未满时,两个线程都可以运行,当Buffer为空时,Consumer就要等待,直到Buffer不为空,这里就是用event来实现的;同样,当Buffer为满时,Producer就要等待。

来源链接: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1355892

原创粉丝点击