I’m writing a program in c on linux using gcc.
If I’m not using that sleep statement
it will print “thread created” 2,3 or 4 number of times randomly. Can anyone explain me this behavior?
//the following code is just a sample, i know is not really useful to create a thread just to print a string 🙂
void* makeRequest(void* arg) {
printf("Thread created\n");
}
int main(){
pthread_t thr[10];
for(i=0; i<3; i++){
pthread_create(&thr[i], 0, makeRequest, &i);
sleep(1);
}
}
p.s. I included pthread.h and the compile option -pthread
In addition to other remarks,
is incorrect, because
iis a local variable, so&iis the same pointer on all your calls to pthread_createYou generally should make the data pointer to your thread routine -here the thread routine is
makeRequesteither a static pointer, or a unique pointer (unique for each thread); in practice, make it a pointer to somemalloc-ed memoory.A better practice would be declare some
struct my_thread_data_st, to uniquely allocate it in the heap withOr you could have an array of e.g.
int-s, e.g.int num[4];, initialize it appropriately, thenpthread_create(&thr[i], 0, makeRequest, &num[i]);Of course, if
tdis heap-allocated thrumalloc, don’t forget tofreeit at the appropriate time, e.g. after the thread ended (e.g. after having pthread_join-ed it). You might be also interested by Boehm’s GC and useGC_mallocinstead ofmalloc(then, don’t bother about freeing memory, the GC will do it).If the threads are accessing a shared data, you should serialize access to it with some [global or static] mutex (using
pthread_mutex_lock&pthread_mutex_unlock)Don’t forget to call
pthread_joinon all your threads before exiting -e.g. returning frommain.I suggest reading some pthreads tutorial and some book on advanced linux programming.