线程互斥
大部分情况下,线程使用的数据都是局部变量,变量的地址空间在线程栈空间内,这种情况变量归属单个线程,其他线程无法获得这种变量。
但有时候,很多变量都需要在线程间共享,这样的变量称为共享变量,可以通过数据的共享完成线程之间的交互。多个线程并发的操作共享变量,会带来一些问题。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
int tickets = 1000;
void *routel(void* args) {
const char *name = (const char*)args;
while (true) {
if(tickets > 0) {
usleep(10000);
printf("%s 抢占票号:%d\n", name, tickets--);
} else {
break;
}
}
return nullptr;
}
int main() {
pthread_t t1, t2, t3, t4;
pthread_create(&t1, nullptr, routel, (void*)"thread-1");
pthread_create(&t2, nullptr, routel, (void*)"thread-2");
pthread_create(&t3, nullptr, routel, (void*)"thread-3");
pthread_create(&t4, nullptr, routel, (void*)"thread-4");
pthread_join(t1, nullptr);
pthread_join(t2, nullptr);
pthread_join(t3, nullptr);
pthread_join(t4, nullptr);
;
}








