As described in title:
Write the program to complete the following functions:
1) There is an int type global variable G_flag initial value is 0;
2) Start thread 1 in the mainline call, print "This is Thread1" and set G_flag to 1
3) Start thread 2 in the mainline call, print "This is Thread2" and set G_flag to 2
4) Line program 1 requires thread 2 exit before exiting
5) The main thread exits
when it detects that the G_flag has changed from 1 to 2, or from 2 to 1.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include < Errno.h>int G_flag = 0;pthread_cond_t cond_self_kill;pthread_mutex_t m_kill;pthread_mutex_t m_flag;void *thread_ Child (void *arg) {if (Pthread_mutex_lock (&m_flag)! = 0) {pthread_exit (NULL);} G_flag = (int) arg; printf ("This Is thread%d\n", (int) arg); if (Pthread_mutex_unlock (&m_flag)! = 0) {pthread_exit (NULL);} if ((int) arg = = 1) {if (Pthread_cond_wait (&cond_self_kill, &m_kill)! = 0) {Pthread_exi T (NULL); } printf ("Thread%d exit\n", (int) arg); } else {sleep (2); Pthread_cond_broadcast (&cond_self_kill); printf ("thread%d exit\n", (int) arg); }pthread_exit (NULL); }int Main (int argc, char *argv[]) {pthread_t child[2];int ret;pthread_cond_init (&cond_self_kill, NULL);p Thread_ Mutex_init (&m_flag, NULL);p thread_mutex_init (&m_kill, NULL); RET = Pthread_create (&child[1], NULL, Thread_child, (void*) 2); if (ret) {return 1;} ret = Pthread_create (&child[0], NULL, Thread_child, (void*) 1); if (ret) {return 1;} if (Pthread_join (child[0], null)! = 0) {pthread_join (child[1], NULL); return 1; } pthread_join (Child[1], NULL); printf ("Main thread exit\n"); return 0;}
Join me in a face test.-linux Threading Programming