Multithreaded C program.

Jul 14, 2014 at 10:55am
Hi,

I want to develop an application for do simultaneous process. For this requirement I decided to use pthreads. So I wrote a c code for that. But the problem is memory usage of the application is increasing when I create a thread.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

void *testFunction(void *para){
  int *id = (int *)para;
  print("Test print ID : %d\n",*id);
  pthread_exit(para);
}

int main(){
  int *count = 0;
  while(1){
     *count++;
     pthread_t handelThread;
     pthread_create(&handelThread,NULL,testFunction,(void *)count);
     usleep(10);
  }
}  


any help?

Thank you.
Jul 14, 2014 at 12:34pm
If you are not planning to join the thread (using pthread_join()) you should detach the thread so that it will clean up as soon as it terminates instead of waiting for it it be joined.

You can do this by calling pthread_detach().
 
pthread_detach(handelThread);

Or by passing thread attributes when creating the thread.
1
2
3
4
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&handelThread,&attr,testFunction,(void *)count);
Jul 14, 2014 at 2:48pm
If you're just starting, try to use C++11 std::future/std::thread, it'll simply your life.
Jul 15, 2014 at 4:33am
Hi.

Thank you all. I'll try. :)
Jul 15, 2014 at 10:59am
Hi,

Problem solved. Thank you all.
Topic archived. No new replies allowed.