在 C 语言中实现多线程并发编程时可以使用 pthread 库中的 pthread_mutex_t 来实现线程锁。
下面是一个示例代码:
#include <pthread.h>
pthread_mutex_t mutex;
void* thread_func(void* arg) {
pthread_mutex_lock(&mutex);
// 临界区代码
pthread_mutex_unlock(&mutex);
}
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, thread_func, NULL);
pthread_create(&thread2, NULL, thread_func, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_mutex_destroy(&mutex);
}