c++11pthread头⽂件解析
⼀、c++ 11 新标准⽀持多线程编程了。
std::thread 在 <thread> 头⽂件中声明,因此使⽤ std::thread 时需要包含 <thread> 头⽂件。
⾸先我们来看⼀个例⼦:
#include <iostream>
#include <thread>
void my_thread()
{
std::cout << "hello word" << std::endl;
}
int main(int argc, char *argv[])
{
std::thread t(my_thread);
t.join();
return 0;
}
⾸先创建⼀个线程对象t,然后⽤my_thread来初始化,实际上使⽤my_thread来实例化⼀个线程对象t,现在线程t在创建完成后将被执⾏,t.join()的作⽤是等待⼦线程my_thread执⾏完之后,主线程才可以继续执⾏下去,然后主线程会释放掉执⾏完后的⼦线程的资源。
下⾯再看⼀个例⼦:传多个参数。
#include <iostream>
#include <stdlib.h>
system的头文件#include <thread>
#include <string>
void my_thread(int num, const std::string& str)
{
std::cout << "the number is: " << num << std::endl;
std::cout << str << std::endl;
}
int main(int argc, char *argv[])
{
int num = 100;
std::string str = "chenxun is a good student.";
std::thread t(my_thread, num, str);
t.detach();
system("pause");
return 0;
}
其中detach()过后主线程对⼦线程不再有控制权了,⼦线程⾃⼰执⾏释放资源。
⼆、互斥量
多个线程同时访问共享资源的时候需要需要⽤到互斥量,当⼀个线程锁住了互斥量后,其他线程必须等待这个互斥量解锁后才能访问它。thread提供了四种不同的互斥量独占式互斥量non-recursive (std::mutex)
递归式互斥量recursive (std::recursive_mutex)
允许超时的独占式互斥量non-recursive that allows timeouts on the lock functions(std::timed_mutex)
独占互斥变量:
独占式互斥量加解锁是成对的,同⼀个线程内独占式互斥量在没有解锁的情况下,再次对它进⾏加锁这是不对的,会得到⼀个未定义⾏为。
如果你想thread1输出10次10,thread2输出10次20,如果你想看到⼀个正确的显⽰效果,下⾯程序是做不到的,因为在thread1输出的时候,thread2也会执⾏,输出的
#include <iostream>
#include <stdlib.h>
#include <thread>
#include <string>
#include <mutex>
int g_num = 0;
std::mutex g_mutex;
void thread1()
{
//g_mutex.lock();
g_num = 10;
for (int i = 0; i<10; i++){
std::cout << "thread1:" << g_num << std::endl;
}
//g_mutex.unlock();
}
void thread2()
{
//std::lock_guard<std::mutex> lg(g_mutex);
g_num = 20;
for (int i = 0; i<10; i++){
std::cout << "thread2:" << g_num << std::endl;
}
}
int main(int argc, char *argv[])
{
std::thread t1(thread1);
std::thread t2(thread2);
t1.join();
t2.join();
system("pause");
return 0;
}
列2:
#include <iostream>      // std::cout
#include <thread>        // std::thread
#include <mutex>          // std::mutex
volatile int counter(0); // non-atomic counter
std::mutex mtx;          // locks access to counter
void attempt_10k_increases()
{
for (int i = 0; i<100; ++i)
{
if (_lock())
{  // only increase if currently not locked:
++counter;
mtx.unlock();
}
}
}
int main(int argc, const char* argv[])
{
std::thread threads[10];
for (int i = 0; i<10; ++i)
threads[i] = std::thread(attempt_10k_increases);
for (auto& th : threads)
th.join();
std::cout << counter << " successful increases of the counter.\n";
return 0;
}