多个线程同时调用某个函数,std::call_once可以保证多线程对该函数只调用一次
#include <iostream>
#include <thread>
#include <mutex>
#include <unistd.h>
std::once_flag flag;
void func() {
std::call_once(flag, [](){
std::cout << "hello world" << std::endl;
sleep(1);
});
}
int main() {
std::thread t1(func);
std::thread t2(func);
std::thread t3(func);
t1.join();
t2.join();
t3.join();
}
pthread_once实现
#include <iostream>
#include <pthread.h>
#include <unistd.h>
pthread_once_t once = PTHREAD_ONCE_INIT;
void print() {
std::cout << "hello world" << std::endl;
sleep(1);
}
void* func(void*) {
pthread_once(&once, print);
}
int main() {
pthread_t tid1, tid2, tid3;
pthread_create(&tid1, NULL, func, NULL);
pthread_create(&tid2, NULL, func, NULL);
pthread_create(&tid3, NULL, func, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_join(tid3, NULL);
}
