这可能是一个愚蠢的问题,但我确实在互联网上搜索了有关变量的所有内容,并找到了与互斥锁和竞速条件、锁等相关的所有内容;但似乎没有什么能解决这个简单的问题。
基本上,下面的代码创建了两个线程,并且在每个线程中,变量shared_int
被更改以表示它所使用的线程。线程单独运行,并且类本身似乎shared_int
在两个不同的线程中有相同变量的两个实例?我遇到的问题是我希望这个变量在任一线程中都可以更改并且也可以读取,但我也希望shared_int
从一个线程看到的值在第二个线程中是相同的。这是代码
#include <boost/thread.hpp>
template <typename I>
class threaded
{
private:
I volatile shared_int;
public:
threaded();
virtual ~threaded();
bool inputAvailable();
void thread_1();
void thread_2();
};
template <typename I>
threaded<I>::threaded(){}
template <typename I>
threaded<I>::~threaded(){}
template <typename I>
bool threaded<I>::inputAvailable()
{
struct timeval tv;
fd_set fds;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds);
select(STDIN_FILENO + 1, &fds, NULL, NULL, &tv);
return (FD_ISSET(0, &fds));
}
template <typename I>
void threaded<I>::thread_1()
{
shared_int = 1;
while(!inputAvailable())
{
std::cout<<"threaded::thread_1 shared_int "<<this->shared_int<<std::endl;
boost::this_thread::sleep_for( boost::chrono::milliseconds{ 9000});
};
}
template <typename I>
void threaded<I>::thread_2()
{
shared_int = 2;
while(!inputAvailable())
{
std::cout<<"threaded::thread_2 shared_int "<<this->shared_int<<std::endl;
boost::this_thread::sleep_for( boost::chrono::milliseconds{ 10000});
};
}
int main()
{
boost::thread_group thread;
threaded< int> threads;
thread.add_thread( new boost::thread( boost::bind( &threaded<int>::thread_1, threads)));
thread.add_thread( new boost::thread( boost::bind( &threaded<int>::thread_2, threads)));
thread.join_all();
return 0;
}