Write a program to open 3 threads, the IDs of the 3 threads are a, B, C, each thread prints its own ID on the screen 10 times

Source: Internet
Author: User
Tags join mutex printf
Write a program, open 3 threads, the IDs of the 3 threads are a, B, C, each thread prints its own ID on the screen 10 times, the output must be displayed in the order of ABC, such as: Abcabc .... recursion in turn. #include  <stdio.h>    #include  <stdlib.h>    #include  <pthread.h >    #include  <unistd.h>    #include  <string.h>   //#define  debug 1    #define &NBSP;NUM&NBSP;3       int n=0;   pthread_ mutex_t mylock=pthread_mutex_initializer;//Mutex    Pthread_cond_t qready=pthread_cond_ initializer;//condition variables          void * thread_func (void *arg)    {       int param= (int) arg;       char c= ' A ' +param;       int ret,i=0;       for  (;  i < 10; i++)        {            pthread_mutex_lock (&mylock);   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;  while  (param != n)   //just running, n = 0, param = 0, Conditions are not set, so print directly a           {   #ifdef  debug                 printf ("thread %d  Waiting\n ",  param);   #endif                 ret = pthread_cond_wait (&qready, &mylock);                if  (ret == 0)                 {   #ifdef  debug     &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;PRINTF (" Thread %d wait success\n ",  param);   #endif                 } else                 {   #ifdef  debug                     printf ("thread %d wait failed:%s\n" ,  param, strerror (ret));   #endif                 }           }           // printf ("%d ", param+1);            printf ("%c ", c);   //print a after             n= (n+1)%num;      //n became 1, The impact on thread 2 will be output ....            pthread_mutex_unlock (&mylock);           //will wake up all the threads, because when the thread finishes, it waits for pthread_cond_wait () to execute two times before exiting while  (param != n)             pthread_cond_broadcast (&qready);                   }            return  (void *) 0;  }      #if  0   // assumed to be thread 2       void * thread_func (VOID&NBSP;*ARG)//Incoming value 1   {       int param= (int) arg;       char c= ' A ' +param;        int ret,i=0;       for  (;  i  < 10; i++)        {            pthread_mutex_lock (&mylock);            while  (PAram != n)   //and thread 1 are executed at the same time, so the initial condition is met             {   #ifdef  debug                 printf ("thread %d waiting\n",  param);   #endif                 //execution to this point, waiting for thread 1 to send a signal, when a thread 1 of a print, the value of n also becomes 1, the condition is not established                ret = pthread_ Cond_wait (&qready, &mylock);                if  (ret == 0)                  {   #ifdef  debug                     printf ("thread %d wait success\n",  param);    #endif                } else                 {   #ifdef   DEBUG                     printf ("thread %d wait failed:%s\n",  param, strerror (ret));   #endif                }            }          // printf ("%d   ", param+1);           printf ("%c  ", c);  // This prints the value b           n= (n+1)%num;    // Impact on thread 3 printing c ...            pthread_mutex_unlock (&mylock);   &NBSp;       pthread_cond_broadcast (&qready);        }           return  (void *) 0;   }      #endif       int main (int argc, char**  argv)  {              int i=0,err;        pthread_t tid[NUM];       void *tret;        for (; i<num;i++)        {            err=pthread_create (&tid[i],null,thread_func, (void *) i);            if (err!=0)             {                printf ("Thread_create error:%s\n ", strerror (Err));                exit ( -1);           }        }       for  (i = 0; i < num; i+ +)        {           err =  pthread_join (Tid[i], &tret);           if   (err != 0)            {                printf ("Can not join with  thread %d:%s\n ",  i,strerror (Err));                exit ( -1);           }       }       printf ("\ n");       return 0;   }  
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <
string.h>//#define DEBUG 1 #define NUM 3 int n=0; pthread_mutex_t mylock=pthread_mutex_initializer;//Mutex pthread_cond_t qready=pthread_cond_initializer;//condition variable void *
    Thread_func (void *arg) {int param= (int) arg;
    Char c= ' A ' +param;
    int ret,i=0;
        for (; i <; i++) {pthread_mutex_lock (&mylock);  while (param! = N)//Just run, n = 0, param = 0, the condition is not true, so print a {#ifdef DEBUG printf ("Thread%d waiting\n") directly,
param);
            #endif ret = pthread_cond_wait (&qready, &mylock); if (ret = = 0) {#ifdef DEBUG printf ("Thread%d wait success\n", param); #endif}
            else {#ifdef DEBUG printf ("Thread%d wait failed:%s\n", Param, strerror (ret)); #endif
        }}//printf ("%d", param+1);  printf ("%c", c); After printing a
        N= (n+1)%num;
        n becomes 1, which affects the output of thread 2 ....
		Pthread_mutex_unlock (&mylock);
		
    All threads are awakened because when the thread finishes it waits for pthread_cond_wait () to execute two times before exiting while (param! = N) pthread_cond_broadcast (&qready);
} return (void *) 0;
    } #if 0//assumed to be thread 2 void * Thread_func (void *arg)//Incoming value 1 {int param= (int) arg;
    Char c= ' A ' +param;
    int ret,i=0;
        for (; i <; i++) {pthread_mutex_lock (&mylock);
			while (param! = N)//and thread 1 are executed concurrently, the conditions at the beginning of the condition satisfy {#ifdef DEBUG printf ("Thread%d waiting\n", param); #endif
            Execution to this point, waiting for thread 1 to send a signal, when thread 1 of a print, the value of n also becomes 1, the condition does not set up ret = Pthread_cond_wait (&qready, &mylock);
            if (ret = = 0) {#ifdef DEBUG printf ("Thread%d wait success\n", param); #endif
            } else {#ifdef DEBUG printf ("Thread%d wait failed:%s\n", Param, strerror (ret)); #endif
        }}//printf ("%d", param+1); Printf("%c", c);    At this time the print value B n= (n+1)%num;
        Impact on thread 3 printing c ...
        Pthread_mutex_unlock (&mylock);
    Pthread_cond_broadcast (&qready);
} return (void *) 0;
    } #endif int main (int argc, char** argv) {int i=0,err;
    pthread_t Tid[num];
    void *tret;
        for (; i<num;i++) {Err=pthread_create (&tid[i],null,thread_func, (void *) i);
            if (err!=0) {printf ("Thread_create error:%s\n", strerror (err));
        Exit (-1);
        }} for (i = 0; i < NUM; i++) {err = Pthread_join (Tid[i], &tret);
            if (err! = 0) {printf ("Can not join with thread%d:%s\n", I,strerror (err));
        Exit (-1);
    }} printf ("\ n");
return 0; }
The results are as follows:
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.