<iostream> int g_i = 0; std::mutex g_i_mutex; // protects g_i,用来保护g_i void safe_increment() { const std::lock_guard<std::mutex> lock(g_i_mutex); ++g_i; std::cout << std::this_thread::get_id() << ": " << g_i << '\n';// g_i_mutex自动解锁}int main(){...
int main() { std::thread t1(increment_counter); std::thread t2(increment_counter); t1.join(); t2.join(); return 0; } 在这个示例中,我们使用thread_local关键字为每个线程创建了一个独立的thread_private_counter副本。当我们在不同的线程中调用increment_counter函数时,它们分别操作自己线程的计数器,...
std::thread t1=f(); t1.join(); std::thread t2=g(); t2.join(); } std::thread可以返回,同样的,std::thread也可以作为参数 我们也可以将std::thread放入std::vector中,将这些线程当做一个组: #include <vector> #include <thread> #include <algorithm> #include <functional> void do_work(unsig...
std::this_thread::sleep_for(std::chrono::seconds(time)); cout << "hello thread2!" << endl; } int main() { //创建了一个线程对象,传入一个线程函数(作为线程入口函数), //新线程就开始运行了,没有先后顺序,随着CPU的调度算法执行 std::thread t1(threadHandle1, 2); std::thread t2(thread...
std::thread t1; // t1 is not a thread std::thread t2(f1, n + 1); // pass by value std::thread t3(f2, std::ref(n)); // pass by reference std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread ...
#include <iostream> #include <thread> using namespace std; void thread_func() { thread_local int stls_variable = 0; stls_variable += 1; cout << "Thread ID: " << this_thread::get_id() << ", Variable: " << stls_variable << endl; } int main() { thread t1(thread_func);...
#include <thread> #include <future> #include <random> #include <chrono> #include <exception> using namespace std; void doSomething(int num, char c); int main() { try { //开启一个线程(不分离) std::thread t1(doSomething, 5, '.'); ...
#include <thread> #include <future> #include <random> #include <chrono> #include <exception> using namespace std; void doSomething(int num, char c); int main() { try { //开启一个线程(不分离) std::thread t1(doSomething, 5, '.'); ...
int pthread_join(pthread_t thread, void **retval); 参数: thread: 要被回收的子线程的线程 ID retval: 二级指针,指向一级指针的地址,是一个传出参数,这个地址中存储了 pthread_exit () 传递出的数据,如果不需要这个参数,可以指定为 NULL 返回值:线程回收成功返回 0,回收失败返回错误号。
char *msg2 = "Thread 2"; pthread_create(&t1, NULL, print_message, (void *) msg1); pthread_create(&t2, NULL, print_message, (void *) msg2); 在这个例子中,两个线程会同时访问printf()函数,可能会导致输出结果错乱。 解决方法:使用同步机制来保证线程之间的正确协作。