C言語でのマルチスレッドロック方法は何ですか。
C言語では、Mutex(ミューテックス)を使用してマルチスレッディングのロックを実現することができます。
一般的な互い排他的なロックの使用手順は次の通りです:
- プログラム内でmutex変数を定義する場合は、pthread_mutex_t型の変数を使用してmutexを表現することができます。
- 共有リソースを保護する必要がある場合、pthread_mutex_lock関数を使用してミューテックスをロックします。
- 共有リソースを操作する。
- 互斥ロックを解除するために、pthread_mutex_unlock関数を使用します。
以下はサンプルコードです:
#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;
}
上記の例では、mutexという排他的な変数が定義され、2つのスレッドでそのmutexをロックおよびアンロックする操作が行われています。これにより、同時に1つのスレッドだけが共有リソースにアクセスできることが保証されます。