Multithreaded programming under Linux (1)

Source: Internet
Author: User

#include <stdio.h>#include<pthread.h>#include<string.h>#include<sys/time.h>#defineMAX 20//define three threads to complete a count task togetherpthread_t thread[3];p thread_mutex_t mut;//Defining Mutex Variablesintnum=0;inti;void*Thread1 () {printf ("Thread1:im Thread 1");  for(i=0; i<max;i++) {printf ("thread1:num=%d \ n", num); Pthread_mutex_lock (&mut); Num++; Pthread_mutex_unlock (&mut); Sleep (2); } pthread_exit (NULL);}void*thread2 () {printf ("Thread1:im Thread 1");  for(i=0; i<max;i++) {printf ("thread1:num=%d \ n", num); Pthread_mutex_lock (&mut); Num++; Pthread_mutex_unlock (&mut); Sleep (2); } pthread_exit (NULL);}void*thread3 () {printf ("Thread1:im Thread 1");  for(i=0; i<max;i++) {printf ("thread1:num=%d \ n", num); Pthread_mutex_lock (&mut); Num++; Pthread_mutex_unlock (&mut); Sleep (2); } pthread_exit (NULL);}voidMain () {Pthread_mutex_init (&mut,null);//using default properties to initialize mutex locksPthread_create (&thread[0],null,thread1,null);//Create thread does not runPthread_create (&thread[1],null,thread1,null); Pthread_create (&thread[2],null,thread1,null); Pthread_join (thread[0],null);//Add thread 1 to wait to start executionPthread_join (thread[1],null); Pthread_join (thread[2],null);}

Multithreaded programming under Linux (1)

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.