C语言中线程间通信的方式有多种,以下是几种常用的方法:
-
全局变量和互斥锁(Mutex):
使用全局变量来存储线程之间共享的数据,并使用互斥锁来确保对共享数据的互斥访问。#include <pthread.h> #include <stdio.h> #include <stdlib.h> int shared_data = 0; pthread_mutex_t lock; void *thread_func(void *arg) { pthread_mutex_lock(&lock); shared_data++; printf("Thread %d: %dn", *(int *)arg, shared_data); pthread_mutex_unlock(&lock); return NULL; } int main() { pthread_t threads[2]; int thread_ids[2] = {1, 2}; pthread_mutex_init(&lock, NULL); for (int i = 0; i < 2; i++) { pthread_create(&threads[i], NULL, thread_func, &thread_ids[i]); } for (int i = 0; i < 2; i++) { pthread_join(threads[i], NULL); } pthread_mutex_destroy(&lock); return 0; }
-
条件变量(Condition Variable):
条件变量可以用来让一个线程等待另一个线程发出某个信号,以实现线程间的同步。#include <pthread.h> #include <stdio.h> #include <stdlib.h> int ready = 0; pthread_mutex_t lock; pthread_cond_t cond; void *thread_func(void *arg) { pthread_mutex_lock(&lock); while (!ready) { pthread_cond_wait(&cond, &lock); } printf("Thread %d is runningn", *(int *)arg); pthread_mutex_unlock(&lock); return NULL; } int main() { pthread_t threads[2]; int thread_ids[2] = {1, 2}; pthread_mutex_init(&lock, NULL); pthread_cond_init(&cond, NULL); for (int i = 0; i < 2; i++) { pthread_create(&threads[i], NULL, thread_func, &thread_ids[i]); } sleep(1); // 模拟一些操作 pthread_mutex_lock(&lock); ready = 1; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&lock); for (int i = 0; i < 2; i++) { pthread_join(threads[i], NULL); } pthread_mutex_destroy(&lock); pthread_cond_destroy(&cond); return 0; }
-
信号量(Semaphore):
信号量可以用来控制对共享资源的访问。#include <pthread.h> #include <semaphore.h> #include <stdio.h> #include <stdlib.h> sem_t sem; void *thread_func(void *arg) { sem_wait(&sem); printf("Thread %d is runningn", *(int *)arg); sem_post(&sem); return NULL; } int main() { pthread_t threads[2]; int thread_ids[2] = {1, 2}; sem_init(&sem, 0, 1); for (int i = 0; i < 2; i++) { pthread_create(&threads[i], NULL, thread_func, &thread_ids[i]); } for (int i = 0; i < 2; i++) { pthread_join(threads[i], NULL); } sem_destroy(&sem); return 0; }
这三种方法是C语言中常用的线程间通信方式,每种方法都有其适用的场景和优缺点,具体选择哪种方法需要根据具体的应用需求来决定。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/192679.html