https://blog.csdn.net/dxyt2002/article/details/130209169
#include <iostream>
#include <unistd.h>
#include <pthread.h>
using std::cout;
using std::endl;
int tickets = 10000;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 定义全局锁, 并用宏来初始化
void* grabTicket(void* args) {
const char* name = static_cast<const char*>(args);
while (true) {
pthread_mutex_lock(&mutex); // 在即将进入临界区时加锁
if (tickets > 0) {
printf("%s: %lu 抢到票了, 编号为: %d\n", name, pthread_self(), tickets--);
pthread_mutex_unlock(&mutex); // 在即将离开临界区时解锁
usleep(10);
}
else {
printf("没有票了, %s: %lu 放弃抢票\n", name, pthread_self());
pthread_mutex_unlock(&mutex); // 在线程即将退出时解锁
break;
}
}
return nullptr;
}
int main() {
pthread_t tid1, tid2, tid3, tid4;
pthread_create(&tid1, nullptr, grabTicket, (void*)"thread_1");
pthread_create(&tid2, nullptr, grabTicket, (void*)"thread_2");
pthread_create(&tid3, nullptr, grabTicket, (void*)"thread_3");
pthread_create(&tid4, nullptr, grabTicket, (void*)"thread_4");
pthread_join(tid1, nullptr);
cout << "main thread join thread_1" << endl;
pthread_join(tid2, nullptr);
cout << "main thread join thread_2" << endl;
pthread_join(tid3, nullptr);
cout << "main thread join thread_3" << endl;
pthread_join(tid4, nullptr);
cout << "main thread join thread_4" << endl;
return 0;
}
这里运行的结果是:
所有票被抢完以后,才依次输出
cout << “main thread join thread_1” << endl;
cout << “main thread join thread_2” << endl;
cout << “main thread join thread_3” << endl;
cout << “main thread join thread_4” << endl;
因为join 限制了一个线程退出以后,才会执行join以后的代码。
但是pthread_create以后,每个线程都已经开始了。他们和主线程是并行的。
如果是detach,那么
cout << “main thread join thread_1” << endl;
cout << “main thread join thread_2” << endl;
cout << “main thread join thread_3” << endl;
cout << “main thread join thread_4” << endl;
这几句话会交错掺杂在抢票结果过程中。抢票未结束的时候主线程就已经退出了。因为进程结束,所以所有线程都杀死。