LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 11-29-2005, 05:21 PM   #1
naihe2010
Member
 
Registered: Oct 2005
Location: China
Distribution: ArchLinux
Posts: 103

Rep: Reputation: 15
How to use mutithread in C ?


I am studing mutithread programing in C, and meet a difficuty.
The source code is:
Code:
#include <string.h>
#include <pthread.h>

#define N 26

void disp(void *str);

int main(void)
{
  int i;
 
  char *chp;
  chp = (char*)malloc(sizeof(char) * N);
  for(i=0; i<N; *(chp+i)='a'+i++);

  pthread_t *thread;
  thread = (pthread_t*)malloc(sizeof(pthread_t) * N);

  for(i=0; i<N; ++i)pthread_create(thread+i, 0, (void*)&disp, (void*)(chp+i));
  sleep(1);
  
  putchar('\n');
  
  return 0;
}

void disp(void *str)
{
  char *strtemp;
  strtemp = (char*)str;
  putchar(*strtemp);
}
As you see, I use a word "sleep(1);" in the 20th line.
If I didn't use this, it can't work well.
What's the problem with my code, and why I must use the "sleep(1)" ?

Please help me.
 
Old 11-29-2005, 06:43 PM   #2
BrianK
Senior Member
 
Registered: Mar 2002
Location: Los Angeles, CA
Distribution: Debian, Ubuntu
Posts: 1,334

Rep: Reputation: 51
threads are not attached to the current process and the current process knows nothing about the thread execution. Because of this, without the sleep, the program continues to run & exits before all the threads complete. The sleep allows all threads to complete.

As a test, but the sleep after the putchar('\n'); you'll see the remainder of your output will show up as soon as the sleep stops blocking output from the main process

To fix, you'll need to include semaphors so that your process knows to wait for all threads to finsih before continuing.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 05:42 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration