Use of pthread parallel computing mutex lock

Source: Internet
Author: User

Because pthread implements parallel computing based on shared memory, the use of shared variables in multiple threads has many synchronization problems. It may be okay to read the same variable in multiple threads, but it may cause inconsistency of the variable content during modification. To solve this problem, you need to perform mutex access to the shared variables.

To implement this function, a thread lock is provided in pthread. The above problems can be easily avoided by locking and unlocking. The specific example is as follows:

#include<iostream>#include<pthread.h>#include<stdlib.h>#include<vector>using namespace std;vector<int> vec;pthread_mutex_t mutex;int thread_count;void *hello(void* a){  
Int AA = (INT) A; pthread_mutex_lock (& mutex); // lock Vec. push_back (AA); pthread_mutex_unlock (& mutex); // unlock} int main () {pthread_t threads [4]; thread_count = 4; pthread_mutex_init (& mutex, null ); for (INT thread = 0; thread <thread_count; thread ++) {pthread_create (& threads [thread], null, hello, (void *) thread ); // hello is the function that the new thread will execute, and the thread is the parameters} cout <"I Am Main. "<Endl; CIN> thread_count; For (INT I = 0; I <thread_count; I ++) {pthread_join (threads [I], null ); // stop all the threads} vector <int>: iterator it; for (IT = Vec. begin (); it! = Vec. End (); It ++) // print the result cout <* It <Endl; // free (threads );}

In the above Code, multiple threads are used to add elements to the vector and print them out in the main thread. Note that if the mutex lock is not used in Hello, the program runs incorrectly. It may be because the pthread has internal restrictions on multithreading to avoid similar errors.

Use of pthread parallel computing mutex lock

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.