c++ - Thread-safe CreateThread? -


is printhello() function pthreads example thread-safe? find these kind of examples online don't understand how can thread-safe. on other hand, if add mutex around code in printhello() function example not multithreaded threads queue in wait previous thread exit printhello() function. also, moving class not member have statically declared pointers non-static functions not allowed createthread() seems. way of solving this?

#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 , 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 execute             (lpthread_start_routine)&printhello,             // thread argument             null,             // start new thread             0,              // thread id             &nthreadid         );            if (!threads[t]){          printf("error; return code createthread() %d\n", getlasterror());          exit(-1);       }    } } 

since you're including winbase.h, i'll assume you're using msvc. msvc crt has long supported multithreaded access - in fact, current versions of msvc no longer support single threaded crt isn't threadsafe. believe vs 2003 last version of msvc supported single threaded crt.

in multithreaded crt, functions threadsafe , if access global data internally synchronize among themselves. each printf() executed in processrequest() atomic respect other printf() calls in other threads (actually, locks based on streams, printf() calls atomic respect other crt functions use stdout).

the exceptions if use i/o functions explicitly documented not take locks (so can synchronize on them performance reasons), or if define _crt_disable_perfcrit_locks in case crt assumes i/o performed on single thread.

see http://msdn.microsoft.com/en-us/library/ms235505.aspx

posix makes similar guarantees printf() threadsafe:


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -