在多線程編程中,線程間的通信是實現任務並行跟合作的關鍵。C言語作為一種底層編程言語,供給了多種機制來實現線程間的通信。本文將具體剖析C言語中線程通信的多少種方法,幫助開辟者控制高效合作的法門。
一、線程間通信概述
線程間通信(Inter-Thread Communication,簡稱ITC)是指在多線程順序中,差別線程之間停止數據交換跟信息轉達的過程。有效的線程間通信可能進步順序的效力,避免數據競爭跟逝世鎖等成績。
二、C言語線程間通信方法
1. 共享內存
共享內存是線程間通信最直接的方法,允很多個線程拜訪同一塊內存地區,從而實現數據的共享。
示例代碼:
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = shm_open("/myshm", O_CREAT | O_RDWR, 0666);
ftruncate(fd, sizeof(int));
int *ptr = mmap(0, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
*ptr = 10;
return 0;
}
2. 旌旗燈號量
旌旗燈號量是一種用於把持多個線程對共享資本的拜訪的同步原語。
示例代碼:
#include <semaphore.h>
#include <pthread.h>
sem_t sem;
void threadfunc(void *arg) {
sem_wait(&sem); // 拜訪共享資本
// ...
sem_post(&sem);
}
int main() {
sem_init(&sem, 0, 1);
pthread_t tid;
pthread_create(&tid, NULL, threadfunc, NULL);
// ...
}
3. 消息行列
消息行列供給了一種非同步的線程間通信方法,容許線程發送跟接收消息。
示例代碼:
#include <sys/ipc.h>
#include <sys/msg.h>
struct msgbuf {
long msg_type;
char msg_text[256];
};
int msgid = msgget(IPC_PRIVATE, 0666 | IPC_CREAT);
void threadfunc(void *arg) {
struct msgbuf msg;
msg.msg_type = 1;
strcpy(msg.msg_text, "Hello");
msgsnd(msgid, &msg, sizeof(msg.msg_text), 0);
}
int main() {
pthread_t tid;
pthread_create(&tid, NULL, threadfunc, NULL);
// ...
}
4. 管道
管道是用於線程間通信的一種簡兩邊法,數據只能單向活動。
示例代碼:
#include <unistd.h>
int main() {
int pipefd[2];
pipe(pipefd);
if (fork() == 0) {
close(pipefd[0]);
write(pipefd[1], "Hello", 5);
close(pipefd[1]);
} else {
close(pipefd[1]);
char buf[10];
read(pipefd[0], buf, 5);
close(pipefd[0]);
printf("%s\n", buf);
}
return 0;
}
5. 互斥鎖
互斥鎖用於保護共享資本,避免多個線程同時拜訪。
示例代碼:
#include <pthread.h>
pthread_mutex_t mutex;
void threadfunc(void *arg) {
pthread_mutex_lock(&mutex);
// 拜訪共享資本
pthread_mutex_unlock(&mutex);
}
int main() {
pthread_t tid;
pthread_mutex_init(&mutex, NULL);
pthread_create(&tid, NULL, threadfunc, NULL);
// ...
}
三、總結
控制C言語線程通信的多少種方法,可能幫助開辟者實現高效合作的多線程順序。在現實開辟中,應根據具體須要抉擇合適的通信方法,避免數據競爭跟逝世鎖等成績。