C Multi-threading: Implementing Mutex Locks

In C language, you can use Mutex to implement locking for multi-threading.

The general steps for using a mutex are as follows:

  1. To define a mutex variable in the program, you can use a variable of type pthread_mutex_t to represent the mutex.
  2. Use the pthread_mutex_lock function to lock the mutex in places where shared resources need protection.
  3. Operate on shared resources.
  4. Unlock the mutex by using the pthread_mutex_unlock function.

The sample code is as follows:

#include <stdio.h>
#include <pthread.h>

pthread_mutex_t mutex;  // 定义互斥锁

void* thread_func(void* arg) {
    pthread_mutex_lock(&mutex);  // 加锁
    // 对共享资源进行操作
    printf("Thread #%ld is working...\n", (long)arg);
    pthread_mutex_unlock(&mutex);  // 解锁
    return NULL;
}

int main() {
    pthread_t thread1, thread2;
    
    pthread_mutex_init(&mutex, NULL);  // 初始化互斥锁
    
    pthread_create(&thread1, NULL, thread_func, (void*)1);
    pthread_create(&thread2, NULL, thread_func, (void*)2);
    
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    
    pthread_mutex_destroy(&mutex);  // 销毁互斥锁
    
    return 0;
}

In the example above, a mutex variable is defined, and lock and unlock operations are performed on the mutex variable in two threads. This ensures that only one thread can access the shared resource at any given time.

bannerAds