您的位置:首页 > 编程语言

一些多线程编程的例子(转)

2009-06-13 12:58 495 查看
转自 http://www.cppblog.com/gohan/archive/2007/02/16/18822.html

Someone recently asked me what I recommend for synchronizing worker threads and I suggested setting an event. This person's response was that you could not do that since worker threads do not support a message pump (UI threads are required to support messages). The confusion here is that events and messages are different animals under windows.

我忘记了我从哪里copy的这些例子代码,他们可是非常简单而有趣的。如果有人知道这些代码的作者,我一定要好好感谢你和这位作者。

注意这里有很多对于没有提及的MFC的支持。像_beginthreadex(一个C运行时库调用)的API可以在MFC应用程序中替换成AfxBeginThread。(建议在mfc情况下也用_beginthreadex)

无同步(No Synchronization

这第一个例子描述了两个互不同步的线程。进程中的首要线程--主函数循环,输出全局整形数组的内容。还有一个线程“Thread”不停的给数组每个元素+1。

The thread called "Thread" continuously populates the global array of integers.

Code
#include <windows.h>
#include <process.h>
#include <stdio.h>

HANDLE hEvent1, hEvent2;
int a[ 5 ];

void Thread( void* pParams )
{
int i, num = 0;

while ( TRUE )
{
WaitForSingleObject( hEvent2, INFINITE );
for ( i = 0; i < 5; i++ ) a[ i ] = num;
SetEvent( hEvent1 );
num++;
}
}

int main( void )
{
hEvent1 = CreateEvent( NULL, FALSE, TRUE, NULL );
hEvent2 = CreateEvent( NULL, FALSE, FALSE, NULL );

_beginthread( Thread, 0, NULL );

while( TRUE )
{
WaitForSingleObject( hEvent1, INFINITE );
printf( "%d %d %d %d %d\n",
a[ 0 ], a[ 1 ], a[ 2 ],
a[ 3 ], a[ 4 ] );
SetEvent( hEvent2 );
}
return 0;
}

Summary of Synchronization Objects

The MSDN News for July/August 1998 has a front page article on Synchronization Objects. The following table is from that article:

Name

Relative speed

Cross process

Resource counting

Supported platforms

Critical Section

Fast

No

No (exclusive access)

9x/NT/CE

Mutex

Slow

Yes

No (exclusive access)

9x/NT/CE

Semaphore

Slow

Yes

Automatic

9x/NT

Event

Slow

Yes

Yes

9x/NT/CE

Metered Section

Fast

Yes

Automatic

9x/NT/CE

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: