C 螺纹僵局静止误锁中止
C++ Threads Deadlock Mutex Lock Aborted
我正在尝试从程序中删除僵局。问题在于该计划不断使我流产。关键是将数据写入文件。但是当僵局发生僵局时,线程应该等待,以后继续而不是流产。
#include <iostream>
#include <unistd.h>
#include <fstream>
#include <vector>
#include <thread>
#include <mutex>
#include <exception>
#include <condition_variable>
using namespace std;
std::mutex mtx;
ofstream myfile;
condition_variable cv;
void lock()
{
mtx.lock();
}
void unlock()
{
mtx.unlock();
}
void writeToFile(int threadNumber){
myfile << "[";
for(int j =1; j <= 10; j++){
int num = j * threadNumber;
string line = std::to_string(num) + " ";
myfile << line;
}
myfile << "]";
//mtx.unlock();
}
void threadFunction(int threadNumber)
{
// int x = 0;
// int y = 0;
try{
lock();
if (threadNumber % 2 == 0)
sleep(rand() % 4 + 1);
writeToFile(threadNumber);
throw exception();
unlock();
}
catch(...){
cout << "Something went wrong!" << endl;
throw exception();
}
}
int main (int argc, char const *argv[]) {
myfile.open ("mutex.txt");
std::set_terminate([](){
std::cout << "Unhandled exceptionn";
// Here I want to fix the deadlock if something goes wrong. But I keep getting Abroted
});
int len;
cout << "Enter Number of threads : ";
cin >> len;
std::thread t[len + 1];
for(int i =1; i <= len;i++){
t[i] = std::thread(threadFunction, i);
cout << "Created Thread : " <<t[i].get_id()<<endl;
}
for(int i =1; i <= len;i++){
t[i].join();
}
myfile.close();
return 0;
}
输出
Enter Number of threads : 5
Created Thread : 1992414288
Created Thread : 1982854224
Created Thread : 1974465616
Created Thread : 1966077008
Created Thread : 1957688400
Something went wrong!
Unhandled exception
Aborted
我如何避免中止且线程等待。
更新:包括所有相关代码...
请勿手动 lock()
/ unlock()
mutexes。那是容易发生的错误。改用后卫。丢弃例外后mtx.unlock();
不会被调用。
这是您的代码外观:
try{
std::lock_guard<std::mutex> lock(mtx);
if (threadNumber % 2 == 0)
sleep(rand() % 4 + 1);
writeToFile(threadNumber);
throw exception();
}
catch(...){
cout << "Something went wrong!" << endl;
throw exception();
}
通常,避免僵局,需要以相反的顺序进行多个静音的锁定和解锁。因此,如果一个线程使用
之类的东西{
std::lock_guard<std::mutex> lock1(mtx1);
std::lock_guard<std::mutex> lock2(mtx2);
// ... exception thrown somewhere
}
这是可以保证的,因为保证std::lock_guard
的损坏器以相反顺序调用。
相关文章:
- 直接显示 - 无法使用设置模式设置静止引脚
- 为什么 boost interprocess_condition notify_one陷入僵局?
- BOOST :: Future延期延续的持续僵局
- C 17原子和条件_Variable僵局
- 除非链接到Pthreads,否则不要僵局
- MPI僵局具有集体功能
- 在带有2D载体的基质类中静止
- 使用STD :: Mutex的僵局模拟
- 打电话给Freelibrary时可能的僵局
- 在Stdout上似乎是僵局
- 如何防止用餐哲学家c++的僵局
- C++生产者消费者陷入僵局
- 为什么这可能导致僵局
- 两个提升的无锁队列会导致僵局
- 带有静音的多个锁和僵局的可能性
- 客户端服务器回声程序进入UDP的僵局
- Mvapich在内核运行时在CUDA内存上僵局
- 等待方法中可能的僵局情况
- 在设计线程安全类时,避免发生僵局
- C 螺纹僵局静止误锁中止