Multi-threaded broadcast

Source: Internet
Author: User

1#include <pthread.h>2#include <stdio.h>3#include <unistd.h>4 5 //static int x = 0;6pthread_mutex_t mutex1 =Pthread_mutex_initializer;7pthread_cond_t Cond1 =Pthread_cond_initializer;8 9 void* DOIT (void*p)Ten { OneSleep (* (int*) (p); APthread_mutex_lock (&mutex1); -     //if (x = = 0) -     { theprintf"pthread_id:%d, wait for command.\n", Pthread_self ()); -Pthread_cond_wait (&cond1,&mutex1); -     } -printf"I%d got Command,let ' s go.\n", Pthread_self ()); +Pthread_mutex_unlock (&mutex1); -     returnNULL; + } A  at  - intMain () - { -pthread_t pth_array[5]; -      -     intI=0; in      for(;i<5; i++) -     { toPthread_create (&pth_array[i],NULL,doit,&i); +     } -      the  *Pthread_mutex_lock (&mutex1); $ Panax NotoginsengPthread_cond_broadcast (&cond1); -Pthread_mutex_unlock (&mutex1); the  +      AI=0; the      for(;i<5; i++) +     { - Pthread_join (pth_array[i],null); $     } $      -     return 0; -}

If a signal (pthread_cond_signal, pthread_cond_broadcast) is signaled, there is no thread in the wait for the condition variable

Wait, the signal is lost and the other threads go to sleep when they come to wait.

Here you can add an X, the value of the broadcast in the number of threads, the thread to determine if its value is 0, then wait, otherwise, minus one, indicating that it received. Therefore, I think the condition variable should be used with a global variable.

Multi-threaded broadcast

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.