Linux C Multithreading

Source: Internet
Author: User

Original: Linux C multithreading

C-language multithreaded programming under Linux

#include <pthread.h>#include<stdio.h>#include<sys/time.h>#include<string.h>#defineMAX 10pthread_t thread[2];p thread_mutex_t mut;intNumber=0, I;void*Thread1 () {printf ("thread1:i ' m thread 1\n");  for(i =0; i < MAX; i++) {printf ("Thread1:number =%d\n", number); Pthread_mutex_lock (&mut); number++; Pthread_mutex_unlock (&mut); Sleep (2); } printf ("THREAD1: Is the main function waiting for me to finish the task? \ n"); Pthread_exit (NULL);}void*thread2 () {printf ("thread2:i ' m thread 2\n");  for(i =0; i < MAX; i++) {printf ("Thread2:number =%d\n", number); Pthread_mutex_lock (&mut); number++; Pthread_mutex_unlock (&mut); Sleep (3); } printf ("THREAD2: Is the main function waiting for me to finish the task? \ n"); Pthread_exit (NULL);}voidThread_create (void){        inttemp; memset (&thread,0,sizeof(thread));//Comment1        /*Creating Threads*/        if(temp = pthread_create (&thread[0], NULL, THREAD1, NULL)!! =0)//Comment2printf"Thread 1 creation failed!\n"); Elseprintf ("thread 1 was created \ n"); if(temp = pthread_create (&thread[1], NULL, THREAD2, NULL)!! =0)//Comment3printf"Thread 2 creation failed"); Elseprintf ("thread 2 was created \ n");}voidThread_wait (void){        /*wait for thread to end*/        if(thread[0] !=0) {//comment4Pthread_join (thread[0],null); printf ("thread 1 has ended \ n"); }        if(thread[1] !=0) {//comment5Pthread_join (thread[1],null); printf ("thread 2 has ended \ n"); }}intMain () {/*initialize mutexes with default properties*/Pthread_mutex_init (&mut,null); printf ("I am the main function Oh, I am creating a thread, hehe \ n");        Thread_create (); printf ("I am the main function oh, I am waiting for the thread to finish the task Ah, OH \ n");        Thread_wait (); return 0;}

Execution results

I am the main function Oh, I am creating thread, hehe thread 1 is created thread 2 is created I am the main function oh, I am waiting for the thread to finish the task Ah, ha thread1:i'm thread 1Thread1:number =0thread2:i'm Thread 2Thread2:number =1Thread1:number=2Thread2:number=3Thread1:number=4Thread2:number=5Thread1:number=6Thread1:number=7Thread2:number=8Thread1:number=9Thread2:number=TenTHREAD1: Is the main function waiting for me to finish the task? Thread 1 has ended THREAD2: is the main function waiting for me to finish the task? Thread 2 has ended

The following is a slightly more complex multithreaded

extern int Pthread_join __p ((pthread_t __th, void **__thread_return));
The first parameter is the waiting thread identifier, and the second parameter is a user-defined pointer that can be used to store the return value of the waiting thread. This function is a thread-blocking function, and the thread that invokes it waits until the thread that is waiting ends, and when the function returns, the resource that is waiting for the thread is retracted. There are two ways to end a thread, one is like our example above, the function ends, the thread that calls it ends, and the other is implemented by the function Pthread_exit. Its function prototypes are:
extern void Pthread_exit __p ((void *__retval)) __attribute__ ((__noreturn__));
The only argument is the return code of the function, as long as the parameter retval in Pthread_exit is not NULL, this value is passed to Thread_return. Finally, one thread cannot be waited by multiple threads, or the first line that receives the signal Cheng returns, and the remaining thread that calls Pthread_join returns the error code esrch.

Instance:

#include <stdio.h>#include<pthread.h>#include<stdlib.h>pthread_t tid1, Tid2;void*Tret;void*Thr_fn1 (void*Arg) {Sleep (1);//sleep a second and wait for TID2 to end. Pthread_join (Tid2, &tret);//Tid1 has been blocking the race until Tid2 's exit, get TID2 's exit codeprintf"thread 2 exit code%d\n", (int) Tret); printf ("Thread 1 returning\n"); return((void*)2);}void*thr_fn2 (void*Arg) {printf ("Thread 2 exiting\n"); Pthread_exit ((void*)3);}intMain (void){    interr; Err= Pthread_create (&tid1, NULL, THR_FN1, NULL); if(Err! =0) printf ("can ' t create thread 1\n"); Err= Pthread_create (&Tid2, NULL, THR_FN2, NULL); if(Err! =0) printf ("can ' t create thread 2\n"); Err= Pthread_join (Tid1, &tret);//wish the thread has been blocking the race, waiting for the return of TID1.     if(Err! =0) printf ("can ' t join with thread 1\n"); printf ("thread 1 exit code%d\n", (int) Tret); //err = Pthread_join (Tid2, &tret); //if (err! = 0)//printf ("can ' t join with thread 2\n");//printf ("Thread 2 exit Code%d\n", (int) tret);Exit0);} Command: #gcc-lthread myfile11-3. C: #./A. outRun Result: Thread2Exitingthread2Exit code3Thread1Returningthread1Exit code2

Linux C Multithreading

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.