读书人

多线程编程中的有关问题

发布时间: 2013-08-06 16:47:25 作者: rapoo

多线程编程中的问题
这是《win32多线程程序设计》中的一个例子,但是有一点我不懂。
各位帮帮看一下,先贴结果:多线程编程中的有关问题


为什么结果中会有超过3个的slot X idle in thread。照理来说,就应该有2个啊。
循环6次,slot分别是0,1,2,0,1,2。不解。代码如下。

/*
* TaskQueS.c
*
* Sample code for "Multithreading Applications in Win32"
* This is from Chapter 3, Listing 3-2
*
* Call ThreadFunc NUM_TASKS times, using
* no more than THREAD_POOL_SIZE threads.
* This version uses WaitForSingleObject,
* which gives a very suboptimal solution.
*
* Build command: cl /MD TaskQueS.c
*/

#define WIN32_LEAN_AND_MEAN
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include "MtVerify.h"

DWORD WINAPI ThreadFunc(LPVOID);

#define THREAD_POOL_SIZE 3
#define MAX_THREAD_INDEX THREAD_POOL_SIZE-1
#define NUM_TASKS 6

int main()
{
HANDLE hThrds[THREAD_POOL_SIZE];
int slot = 0;
DWORD threadId;
int i;
DWORD exitCode;

/* i= 1 2 3 4 5 6 7 8 9
* Start Thread X X X X X X
* Wait on thread X X X X X X
*/
for (i=1; i<=NUM_TASKS; i++)
{
if (i > THREAD_POOL_SIZE)
{

WaitForSingleObject(hThrds[slot], INFINITE);

MTVERIFY( GetExitCodeThread(hThrds[slot], &exitCode) );

printf("Slot %d terminated\n", exitCode );
MTVERIFY( CloseHandle(hThrds[slot]) );
}



MTVERIFY( hThrds[slot] = CreateThread(NULL,
0,
ThreadFunc,
(LPVOID)slot,
0,
&threadId ) );

printf("Launched thread #%d (slot %d)\n", i, slot);
if (++slot > MAX_THREAD_INDEX)
slot = 0;
}
for (slot=0; slot<THREAD_POOL_SIZE; slot++)
{

WaitForSingleObject(hThrds[slot], INFINITE);
MTVERIFY( CloseHandle(hThrds[slot]) );
}
printf("All slots terminated\n");

return EXIT_SUCCESS;
}

/*
* This function just calls Sleep for
* a random amount of time, thereby
* simulating some tasks that takes time.
*
* The param "n" is the index into
* the handle array, kept for informational
* purposes.
*/
DWORD WINAPI ThreadFunc(LPVOID n)
{
srand( GetTickCount() );

Sleep((rand()%8)*500+500);
printf("Slot %d idle in thread\n", n);
return ((DWORD)n);
}

多线程
[解决办法]
因为 THREAD_POOL_SIZE?是3
[解决办法]
设置 project setting --- c++(code generation ) use run-time library debug multithreaded dll


因为createthread 不适合多线程用了,如果你用了c函数。

读书人网 >VC/MFC

热点推荐