您可以从线程池中选择要执行的线程(boost)
这是我在atm机上得到的一些代码您可以从线程池中选择要执行的线程(boost),boost,boost-asio,boost-thread,Boost,Boost Asio,Boost Thread,这是我在atm机上得到的一些代码 int main() { boost::thread_group threads; // Thread Pool // Here we create threads and kick them off by passing // the address of the function to call for (int i = 0; i < num_threads; i++) threads.create_thre
int main()
{
boost::thread_group threads; // Thread Pool
// Here we create threads and kick them off by passing
// the address of the function to call
for (int i = 0; i < num_threads; i++)
threads.create_thread(&SendDataToFile);
threads.join_all();
system("PAUSE");
}
void SendDataToFile()
{
// The lock guard will make sure only one thread (client)
// will access this application at once
boost::lock_guard<boost::mutex> lock(io_mutex);
for (int i = 0; i < 5; i++)
cout << "Writing" << boost::this_thread::get_id() << endl;
}
目前我只是使用cout而不是写入文件
是否可以在另一个线程之前选择一个线程来执行操作。所以我有一个文件我想写,4个线程想同时访问该文件,我可以说ok线程2你先去吗?增强
fstream可以像cout一样使用吗?当我写入一个文件时,如果没有互斥锁,输出不是很混乱吗?但是,当我在没有互斥锁的情况下打印到控制台时,它会像您预期的那样混乱。有许多等效的方法,您可以使用受原子更新保护的全局变量、互斥锁、信号量、条件变量、,在我看来,最直接地传达您正在尝试做的事情的方式是让您的线程等待一个进程,而不是它们的票证号代表它们到达锁的顺序,而是选择线程创建的顺序。您可以将此想法与结合起来,以实现一个简单且可能性能良好的实现。链接可能会有所帮助@user2202911是否有关于此的增强示例?我不知道有任何示例-抱歉。您能更具体一点吗?如果希望在SendDataToFile函数中获取子线程的索引,可以使用boost::bind。如果您想先启动一个子线程,只需先单独启动线程,然后等待线程连接*