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