我已经做了一个简单的线程安全的hmmscan_fun () {
local file=$1
local marker_profiles=$2
local n_threads=$3
local out_dir=$4
fname=$(echo $file | rev | cut -d'/' -f1 | rev)
echo 'filename'
echo $out_dir$fname".txt"
echo 'n threads'
echo $n_threads
echo 'marker profiles'
echo $marker_profiles
echo $out_dir$fname".txt" >> $out_dir"out.txt"
hmmscan -o $out_dir$fname".txt" --tblout $out_dir$fname".hmm" -E 1e-10 --cpu $n_threads $marker_profiles $file
}
实现,创建了10个线程在Buffer
队列上工作,以随机推送和弹出一些数字。我的实现应让等待弹出的线程仅等待3秒,然后终止。发生这种情况时,我会显示超时消息。
问题是仅打印一条超时消息,然后主线程将加入所有线程并返回。为什么?
这是代码main.cpp
buffer
Buffer.h
#include <thread>
#include <vector>
#include <iostream>
#include <sstream>
#include "Buffer.h"
int main() {
std::vector<std::thread> workers;
Buffer<std::string> buffer(3);
srandom(time(NULL));
for (int i = 0; i < 10; i++) {
workers.emplace_back([&buffer]{
long num = random();
if(num%2==0) {
std::stringstream msg;
msg << std::this_thread::get_id() << " pushing " << num << std::endl;
std::cout << msg.str();
buffer.push(std::to_string(num));
} else {
std::stringstream msg1;
msg1 << std::this_thread::get_id() << " waiting to pop" << std::endl;
std::cout << msg1.str();
std::string popped_string = buffer.pop();
std::stringstream msg2;
msg2 << std::this_thread::get_id() << " popped " << popped_string << std::endl;
std::cout << msg2.str();
}
});
}
for (auto &w: workers) {
if (w.joinable()) w.join();
}
return 0;
}