Introduction to Multi-Threaded Programming

A description of POSIX thread basics for C programmers.
______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

there are errors when linking

shindow's picture

shindow@shindow-laptop:~/code$ gcc thread.c -o thread
/tmp/ccXY7Wqj.o: In function `main':
thread.c:(.text+0x40): undefined reference to `pthread_create'
thread.c:(.text+0x6e): undefined reference to `pthread_join'
collect2: ld returned 1 exit status

i check it at :http://stackoverflow.com/questions/1662909/undefined-reference-to-pthread-create-in-linux-c-programming

so gcc -pthread thread.c -o thread is correct

Excellent

Anonymous's picture

Hi,

First of all thanks for this tutorial. Its simple and very clear.
All mistakes in the sample example were already mentioned by others :)
Even I used

while(1) {
pthread_mutex_lock(&count_mutex);
if(x == 4000) {
pthread_mutex_unlock(&count_mutex);
pthread_exit(NULL);
return;
}
x++;
printf("Thread ID%ld: X is now %d.\n",
pthread_self(), x);
pthread_mutex_unlock(&count_mutex);
}

which will ensure x value to be 4000. See I got it from your tutorial :D.
Thanks again.

Just Add

Anonymous's picture

The follow link is a interesting guide:

https://computing.llnl.gov/tutorials/pthreads/

Tcp Client and Server

Anonymous's picture

How would you create a tcp server and client, whereby the server wants to be able to see any move made by the client and vice versa?[c-sharp]

Did the first commenter

Anonymous's picture

Did the first commenter seriously use goto? GTFO and learn to program.

Accessing the variable "x"

Eric Saint-Etienne's picture

Accessing the variable "x" outside the mutexed area is not really a good idea.
I would rather have used something like this:

void *mythread(void *data) {
start:
  pthread_mutex_lock(&count_mutex);
  if (x < 4000) {
    x++;
    printf("Thread ID%ld: X is now %d.\n", pthread_self(), x);
    pthread_mutex_unlock(&count_mutex);
    goto start;
  }
  else {
    pthread_mutex_unlock(&count_mutex);
  }
  pthread_exit(NULL);
}

This is one of the rare cases where a "goto" is useful ;-)

Thanks for the tutorial.

Restructuring the increment loop

Anonymous's picture

How about this?


bool run=true;
while(run) {
pthread_mutex_lock(&count_mutex);
if(run=(x<4000) x++;
printf("Thread ID%ld: X is now %d.\n",
pthread_self(), x);
pthread_mutex_unlock(&count_mutex);
}

I think changing the

Anonymous's picture

I think changing the increment line to

if (x < 4000) {x++};

would be better, otherwise the count goes higher than 4000 as the while check is outside the mutex. Otherwise, thanks for the example, it was very clear.

code analyzer for multi threaded programming

Antony's picture

Errors in multi threaded application programming like Thread block, Dead lock and Race conditions can also be solved using static tools. Companies like Symbian , Juniper networks ,Research in Motion(Blackberry),Cisco are using Coverity Prevent, a Static analysis code inspection tool for analyzing source code for fixing defects. Coverity Prevent is also used by the Department of Homeland security to scan many open source projects. you can get more info at at http://www.Coverity.com

LinuxThreads and NPTL

maria's picture

Perhaps you would like to revisit
http://pauillac.inria.fr/~xleroy/linuxthreads/
It's stated that "LinuxThreads is now obsolete and is being replaced by NPTL."
Thank you for the introduction.

pthreads is not obsolete.

Anonymous's picture

pthreads is not obsolete. it's just the implemention in glibc and kernel.

Excellent

Anonymous's picture

This is my first MT program, this tutorial gave me a clear idea..wonderful..!!
ThanX a lot..!!

Yes

petrov9's picture

The article helped me to understand.
Thanks...

Compile error with the source code

Omer's picture

I think this line :

pthread_t tid[10];

Should be changed into :

pthread_t tids[10];

Because code uses "tids" instead of "tid" ... a small syntax error.

Thank you for the tutorial it helped a lot.

The sample code is buggy

youssef's picture

Thanks for the tutorial,
I tried the sample code provided in this article. After a small change of the variable name tid to tids, I compiled the program with no errors. However, the result was not what I was expecting .Actually the variable X goes up to 4009 not the expected value 4000. I think it might be because the lock is inside the while loop..further stop condition should be implemented after the thread got the mutex.
thanks

Re: Introduction to Multi-Threaded Programming

Anonymous's picture

Probably should have covered condition variables.

Re: Introduction to Multi-Threaded Programming

Anonymous's picture

i need some more examples programmes for threads.could u send to my id?.my id is " panusuyadevi@yahoo.co.in "
thanku

Re: Introduction to Multi-Threaded Programming

Anonymous's picture

IT is a wonderfull sample...

I would like to know more about pthreads..

could pls assist me where i could get more information and samples --Jai

Re: Introduction to Multi-Threaded Programming

Anonymous's picture

IT is a wonderfull sample...

I would like to know more about pthreads..

could pls assist me where i could get more information and samples

Re: Introduction to Multi-Threaded Programming

Anonymous's picture

Wonderfully written. Convered all the basic issues with MT programming in just a page.

Re: Introduction to Multi-Threaded Programming

Anonymous's picture

Very well written. Simple yet precise.

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState