Linux多线程同步——互斥锁

互斥锁

当多个线程对同一个资源进行访问的时候,为了这个资源的安全性,我们需要对这个资源进行锁定,规定同一时间只有一个资源能够获得该锁的钥匙,其它线程要获得该资源需要等待该线程

互斥锁创建

pthread_mutex_t mutex;

互斥锁初始化

mutex = PTHREAD_MUTEX_INITIALIZER;
或 pthread_mutex_init(&mutex);

互斥锁上锁

pthread_mutex_lock(&mutex);

互斥锁解锁

pthread_mutex_lock(&mutex);

销毁互斥锁

pthread_mutex_destroy(&mutex);

#include <pthread.h>
#include <sys/syscall.h>
#include <stdlib.h>
#include <stdio.h>

void* ret_result_thread1;
void* ret_result_thread2;
pthread_mutex_t mutex;

void* thread1Func(void* arg)
{
     pthread_mutex_lock(&mutex);
         printf("childThread id:%u is running\n", syscall(SYS_gettid));
         sleep(5);
         pthread_mutex_unlock(&mutex);
         pthread_exit((void*)0);
}

int main(int argc, char** argv)
{

      printf("main thread start\n");
      pthread_mutex_init(&mutex,NULL);

      pthread_t thread1,thread2;
      int ret1;
      int ret2;
      if( (ret1 = pthread_create(&thread1,NULL,thread1Func,NULL)) != 0)
      {
             perror("thread1 create failed");
      }

      if( (ret2 = pthread_create(&thread2,NULL,thread1Func,NULL)) != 0)
      {
             perror("thread2 create failed");
      }

      printf("main thread end\n");

      pthread_join(thread1,ret_result_thread1);
      pthread_join(thread2,ret_result_thread2); 

      pthread_mutex_destroy(&mutex);
      return 0;
}

Linux多线程同步——互斥锁_第1张图片
线程1运行,等2秒,线程1释放锁,线程2执行

你可能感兴趣的:(多线程,线程,linux,安全,互斥锁-mutex)