首页 > 技术知识 > 正文

Qt中实现C++线程操作二(线程同步)

线程同步是指同一进程中的多个线程互相协调工作从而达到一致性。之所以需要线程同步,是因为多个线程同时对一个数据对象进行修改操作时,可能会对数据造成破坏。 下面是多个线程同时修改同一数据造成破坏的例子:

#include <thread> #include <iostream> int count = 0; void f1(){ for(int i = 0;i <1000;i++) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); count ++; std::cout << “f1–count:” << count << “\n”; } } void f2(){ for(int i = 0;i <1000;i++) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); count ++; std::cout << “f2–count:” << count << “\n”; } } int main(int argc, char *argv[]) { std::thread t1(f1); std::thread t2(f2); t1.join(); t2.join(); return 0; }
<

运行结果: Qt中实现C++线程操作二(线程同步) 由运行结果可以看出打印的数据并没有像想象的递增并且出现了相同的打印结果,这是因为两个线程同时访问了数据源并对数据源进行修改打印,所以出现了相同的打印结果。 想要解决这个问题就要进行线程同步。 C++的线程同步:mutex锁

#include <thread> #include <mutex> #include <iostream> int count = 0; std::mutex mutex; void f1(){ for(int i = 0;i <1000;i++) { mutex.lock(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); count ++; std::cout << “f1–count:” << count << “\n”; mutex.unlock(); } } void f2(){ for(int i = 0;i <1000;i++) { mutex.lock(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); count ++; std::cout << “f2–count:” << count << “\n”; mutex.unlock(); } } int main(int argc, char *argv[]) { std::thread t1(f1); std::thread t2(f2); t1.join(); t2.join(); return 0; }
<

运行结果: Qt中实现C++线程操作二(线程同步)1

加过锁的运行结果就没有再出现过数据打印错乱、重复的问题了,但是使用std::mutex每次都需要加锁和解锁,稍微不注意忘记解锁就会导致再也访问不了数据,使用std::lock_guard可以解决忘记解锁的问题

#include <thread> #include <mutex> #include <iostream> int count = 0; std::mutex mutex; void f1(){ for(int i = 0;i <1000;i++) { std::lock_guard<std::mutex> lock(mutex); std::this_thread::sleep_for(std::chrono::milliseconds(1)); count ++; std::cout << “f1–count:” << count << “\n”; } } void f2(){ for(int i = 0;i <1000;i++) { std::lock_guard<std::mutex> lock(mutex); std::this_thread::sleep_for(std::chrono::milliseconds(1)); count ++; std::cout << “f2–count:” << count << “\n”; } } int main(int argc, char *argv[]) { std::thread t1(f1); std::thread t2(f2); t1.join(); t2.join(); return 0; }
<

猜你喜欢