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:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/flockfile.html
all functions reference (file *) objects, except names ending in _unlocked, shall behave if use flockfile() , funlockfile() internally obtain ownership of these (file *) objects.
http://newsgroups.derkeiler.com/archive/comp/comp.programming.threads/2009-06/msg00058.html (a post david butenhof):
posix/unix requires printf() atomic; it's not legal 2 parallel calls printf() separate threads can mix data. 2 writes may appear on output in either order.
Comments
Post a Comment