函数 pthreads 示例是PrintHello()
线程安全的吗?我在网上找到了这类示例,但我不明白它们如何是线程安全的。另一方面,如果我在PrintHello()
函数中的代码周围添加一个互斥锁,那么该示例将不会是多线程的,因为所有线程都会排队等待前一个线程退出PrintHello()
函数。CreateThread()
此外,将它移动到一个类也无济于事,因为它似乎不允许将成员静态声明为指向非静态函数的指针。有什么办法解决这个问题吗?
#include <WinBase.h>
#include <stdio.h>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#define NUM_THREADS 500
DWORD PrintHello(LPVOID oHdlRequest)
{
long tid;
tid = (long)GetCurrentThreadId();
/* randomly sleep between 1 and 10 seconds */
int sleepTime = rand() % 10 + 1;
sleep(sleepTime);
printf("Hello World! It's me, thread #%ld!\n", tid);
return 0;
}
int main (int argc, char *argv[])
{
/* initialize random seed: */
srand (time(NULL));
HANDLE threads[NUM_THREADS];
long t;
DWORD nThreadID;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
threads[t] = CreateThread(
// Default security
NULL,
// Default stack size
0,
// Function to execute
(LPTHREAD_START_ROUTINE)&PrintHello,
// Thread argument
NULL,
// Start the new thread immediately
0,
// Thread Id
&nThreadID
);
if (!threads[t]){
printf("ERROR; return code from CreateThread() is %d\n", GetLastError());
exit(-1);
}
}
}