如何在本地使用互斥锁变量来锁定线程?

suj*_*jin 0 c linux multithreading mutex pthreads

当我在pthread中编程互斥时,我曾经在pthread_mutex_t mutex全局中使用互斥锁lock().当我看到许多示例程序时,大多数情况下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);
}
Run Code Online (Sandbox Code Playgroud)

我怀疑的是,在这种情况下,程序中的每个地方都可以使用互斥变量并锁定和解锁互斥锁.这会降低安全性.

是否可以通过在线程处理程序中本地创建互斥变量来锁定线程.喜欢以下程序结构

void *add1_fun(void* arg)
{
    pthread_mutex_t mutex;
    pthread_mutex_lock(&mutex);

/* critical section */

    pthread_mutex_unlock (&mutex);
}
int main()
{
   /* code */
}
Run Code Online (Sandbox Code Playgroud)

我认为这个问题可能毫无意义,请帮助我,我不擅长多线程.

我在linux下使用gcc.

谢谢.

Som*_*ude 6

局部变量只是特定函数调用的本地变量.如果您希望"本地"变量在函数调用之间保持静态,那么您必须创建变量static.


yos*_*sim 5

互斥的想法是,每个人都可以尝试锁定它,但是,任何时候只有一个会成功.

如果使用本地互斥锁,则可以将其锁定.但其他线程,将创建自己的本地互斥锁,并将成功锁定它.不是重点,是......

如果你不想使用mutex globaly,你可以将它声明为atatic,然后,每个人都将使用相同的互斥锁.


Tur*_*lin 5

什么是互斥

它是一个用于通过多个线程访问程序资源的对象,但是任何时候只有一个线程可以访问该资源.我不认为您必须从互斥体角度考虑安全性问题,因为一旦锁定,只有锁定它的线程才能解锁它.

所以你要么使互斥体成为全局的,要么是静态的,而不是本地的.