[Country EMBED strategy] [087] [Multithreaded Programming]

Source: Internet
Author: User

Threading Concepts

1. Threading is a lightweight process.

2. The thread shares the code snippet and data segment with the process that created it.

3. Threads have their own stand-alone stacks.

Threading Features

A thread can do the same or different work as a process, but shares resources with the process.

Thread Mutex

In real-world applications, multiple threads tend to access the same data or resource, and in order to avoid interaction between threads, it is necessary to introduce the thread mutex mechanism, which is one of the mutex (mutex) mutex mechanisms.

Thread.c

#include <pthread.h>#include<stdio.h>#include<unistd.h>pthread_mutex_t Mutex;intTask =0;void*thread0 ();void*thread1 ();voidMain () {//Creating Mutex LocksPthread_mutex_init (&mutex, NULL); //Creating child Threadspthread_t thread[2]; Pthread_create (&thread[0], NULL, THREAD0, NULL); Pthread_create (&thread[1], NULL, THREAD1, NULL); //waiting for a child threadPthread_join (thread[0], NULL); Pthread_join (thread[1], NULL);}void*thread0 () {//Show Threadsprintf"I am thread0!\n"); //Processing Tasks    inti;  for(i =0; I <Ten; i++){        //Get Mutex lockPthread_mutex_lock (&mutex); //Processing Taskstask++; //Release Mutex lockPthread_mutex_unlock (&mutex); //Show Tasksprintf"thread0 task:%d\n", Task); //Sleep WaitingSleep1); }        //Exit ThreadPthread_exit (NULL);}void*Thread1 () {//Show Threadsprintf"I am thread1!\n"); //Processing Tasks    inti;  for(i =0; I <Ten; i++){        //Get Mutex lockPthread_mutex_lock (&mutex); //Processing Taskstask++; //Release Mutex lockPthread_mutex_unlock (&mutex); //Show Tasksprintf"Thread1 task:%d\n", Task); //Sleep WaitingSleep1); }        //Exit ThreadPthread_exit (NULL);}

[Country EMBED strategy] [087] [Multithreaded 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.