线程间通信————同步
?????????????????????????????????????????????????? 同步
?
?
是指多個任務按照約定的先后次序 相互配合完成一件事情
?
信號量:
由信號量決定 線程是繼續執行 還是阻塞等待
信號量代表某種資源 其值表示系統中該資源的數量
信號量是一個受保護的量 只能通過特定的三種操作來訪問
初始化
P操作(申請資源, 有可能阻塞)
V操作(釋放資源, 不會阻塞)
?
P(s)操作 :
if(信號量的值大于0 )
申請資源的任務繼續執行 信號量-1
else
申請資源的任務阻塞·
?
V(s)操作 :
信號量+1
if(有任務在等待資源 )
喚醒等待任務 讓其繼續執行
?
Posix信號量
內部定義了兩類信號量:
無名信號量 (基于內存的信號量 主要用于線程間的同步 也可以用于進程之間
但是不方便)
有名信號量(既可以用于進程 也可以用于線程)
?
信號量操作函數:
#include<semaphore.h>
int sem_init(sem_t *sem, int pshared,unsigned int vaule) // 信號量初始化
成功返回0 失敗返回EOF
sem 指向要初始化的信號量對象
pshared 0 - 線程間 1 - 進程間
val 信號量初值
?
同文件同上
int sem_wait(sem_t *sem); //P操作
int sem_post(sem_t *sem); //V操作
成功返回0 失敗返回EOF
sem 指向要操作的信號量對象
Ps: 兩個線程同步讀寫緩沖區
char buf[32];
sem_t sem;
void *function(void *arg);
int main(void)
{
pthread_t a_thread;
if(sem_init(&sem,0, 0) < 0)
{
perror("sem_init");
exit(-1);
}
?
if(pthread_create(&a_thread, NULL, function, NULL) != 0)
{
printf("fila to pthread_create");
exit(-1);
}
?
printf("input 'quit' to exit\n");
?
do{
fgets(buf, 32, stdin);
sem_post(&sem);
}while(strncmp(buf, "quit", 4) != 0);
?
return 0;
}
?
void *function(void *arg)
{
while(1)
{
sen_wait(&sem);
printf("you enter %d characters\n", strlen(buf));
}
}
?
Ps: l兩個線程同步讀寫
?
char buf[32];
sem_t sem_r, sem_w;
void *function(void *arg);
int main(void)
{
pthread_t a_thread;
if(sem_init(&sem_r,0, 0) < 0)
{
perror("sem_init");
exit(-1);
}
if(sem_init(&sem_w,0, 0) < 0)
{
perror("sem_init");
exit(-1);
}
?
if(pthread_create(&a_thread, NULL, function, NULL) != 0)
{
printf("fila to pthread_create");
exit(-1);
}
?
printf("input 'quit' to exit\n");
?
do{
sem_post(&sem_w);
fgets(buf, 32, stdin);
sem_wait(&sem_r);
}while(strncmp(buf, "quit", 4) != 0);
?
return 0;
}
?
void *function(void *arg)
{
while(1)
{
sen_wait(&sem_r);
printf("you enter %d characters\n", strlen(buf));
sen_post(&sem_w);
}
}
?
命令: gcc -o test test.c -lpthread
?
總結
以上是生活随笔為你收集整理的线程间通信————同步的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: exec函数族(部分 最常用的)
- 下一篇: vue-router 不想存历史记录怎么