一、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>
#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)
允许超时的递归式互斥量recursive mutex that allows timeouts on the lock functions (std::recursive_timed_mutex)
独占互斥变量:
独占式互斥量加解锁是成对的,同一个线程内独占式互斥量在没有解锁的情况下,再次对它进行加锁这是不对的,会得到一个未定义行为。
如果你想thread1输出10次10,thread2输出10次20,如果你想看到一个正确的显示效果,下面程序是做不到的,因为在thread1输出的时候,thread2也会执行,输出的结果看起来有点乱(std::cout不是线程安全的),所以我们需要在它们访问共享资源的时候使用互斥量加锁。打开代码里面的三行注释就可以得到正确的结果了。在线程1中std::mutex使用成员函数lock加锁unlock解锁,看起来工作的很好,但这样是不安全的,你得始终记住lock之后一定要unlock,但是如果在它们中间出现了异常或者线程直接退出了unlock就没有执行,因为这个互斥量是独占式的,所以在thread1没有解锁之前,其他使用这个互斥量加锁的线程会一直处于等待状态得不到执行。lock_guard模板类使用RAII手法封装互斥量,在实例化对象的时候帮你加锁,并且能保证在离开作用域的时候自动解锁,所以你应该用lock_guard来帮你加解锁。
#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 (mtx.try_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;
}