?sellticket.c
/*
使用多線程實(shí)現(xiàn)買票的案例。
有3個(gè)窗口,一共是100張票。
*/
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 全局變量,所有的線程都共享這一份資源。
int tickets = 100;
void * sellticket(void * arg) {
// 賣票
while(tickets > 0) {
usleep(6000);
printf("%ld 正在賣第 %d 張門票\n", pthread_self(), tickets);
tickets--;
}
return NULL;
}
int main() {
// 創(chuàng)建3個(gè)子線程
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, NULL, sellticket, NULL);
pthread_create(&tid2, NULL, sellticket, NULL);
pthread_create(&tid3, NULL, sellticket, NULL);
// 回收子線程的資源,阻塞
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_join(tid3, NULL);
// 設(shè)置線程分離。
// pthread_detach(tid1);
// pthread_detach(tid2);
// pthread_detach(tid3);
pthread_exit(NULL); // 退出主線程
return 0;
}
文章來源:http://www.zghlxwxcb.cn/news/detail-612037.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-612037.html
到了這里,關(guān)于基于linux下的高并發(fā)服務(wù)器開發(fā)(第三章)- 3.8 線程同步的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!