Join me in a face test.-linux Threading Programming

Source: Internet
Author: User

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

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.