當我在pthread編程互斥我用來使互斥鎖變量(pthread_mutex_t mutex
)全球。當我看到很多示例程序大部分情況下互斥變量放在全局。如何通過本地使用互斥鎖變量來鎖定線程?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *add1_fun(void* arg);
void *add2_fun(void* arg);
pthread_mutex_t mutex;
void *add1_fun(void* arg)
{
int t_num = (int)arg;
int i = 0;
pthread_mutex_lock(&mutex);
printf("Thread %d created and running \n", t_num); /*critical section start*/
sleep(3);
printf("Thread %d finishes the work\n", t_num); /*critical section end*/
pthread_mutex_unlock (&mutex);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t mythread1;
pthread_t mythread2;
pthread_attr_t myattr;
void *joinResult;
int x = 0;
int t_arg = 1;
pthread_mutex_init(&mutex, NULL);
pthread_attr_init(&myattr);
pthread_attr_setdetachstate(&myattr, PTHREAD_CREATE_JOINABLE);
if((pthread_create(&mythread1, &myattr, add1_fun, (void*)t_arg) != 0)){
printf("Error, thread not created properly\n");
return 1;
}
t_arg = 2;
if((pthread_create(&mythread2, &myattr, add1_fun, (void*)t_arg) != 0)){
printf("Error, thread not created properly\n");
return 1;
}
pthread_attr_destroy(&myattr);
if(pthread_join(mythread1, &joinResult) != 0){
printf("Error pthread join \n");
return 1;
}
printf("Main : Thread1 joined with result of %d\n", (int)joinResult);
if(pthread_join(mythread2, &joinResult) != 0){
printf("Error pthread join \n");
return 1;
}
printf("Main : Thread2 joined with result of %d\n", (int)joinResult);
printf("main finishes the work\n");
pthread_exit(NULL);
}
什麼是我的疑問是,在這種情況下無處不在的程序可以採取互斥鎖變量和 就鎖定和解鎖互斥。這會降低安全性。
是否可以通過在線程處理程序中本地創建互斥鎖變量來鎖定線程。像下面的程序結構
void *add1_fun(void* arg)
{
pthread_mutex_t mutex;
pthread_mutex_lock(&mutex);
/* critical section */
pthread_mutex_unlock (&mutex);
}
int main()
{
/* code */
}
我覺得這個問題可能沒有意義,請幫幫我,我不擅長多線程。
我在linux下使用gcc。
謝謝。
您正在使用「安全」一詞。你有什麼樣的對手和威脅? –