Mọi người cho mình hỏi về pthread với:
Mình đang tự tìm hiểu: vấn đề của mình là điều gì xảy ra khi pthread_create được gọi, nhưng sau đó pthread_join không được sử dụng.
Đây là code minh, họa, mình chưa giải thích được.
// tao 10 thread, moi thread co nhiem vu la in ra gia tri cua bien chua trong doi so cua chung va sau do thoat
#include <pthread.h>
#include <iostream>
/* Declaration of the function which will serve as an argument function for all the threads.*/
void* functionA (void*);
/* Declaration of the global variable which will get incremented by each of the threads in the common function `functionA`.*/
int counter = 0;
/* Declaration and initialization of the mutex variable which will protect the shared global variable `counter`.*/
pthread_mutex_t mutexA = PTHREAD_MUTEX_INITIALIZER;
int main ()
{
/* Declaring an array for 10 threads.*/
pthread_t thread_id [10];
/* Creating 10 threads with default attributes and the common function namely `functionA` for execution.*/
for (int i = 0; i < 10; i++)
{
pthread_create (&thread_id [i], NULL, functionA, NULL);
}
std :: cout << "Final counter value: " << counter << "\n";
return 0;
}
void* functionA (void* arg)
{
/* `pthread_self ()` prints the thread ID of the currently calling thread.*/
std :: cout << "Thread number: " << pthread_self () << "\n";
pthread_mutex_lock (&mutexA);
/* Each time this function gets called, the counter is incremented by the calling thread.*/
counter++;
pthread_mutex_unlock (&mutexA);
return 0;
}
Một số giá trị trả về của chương trình.
Cám ơn mọi người.