开发者

BOOST THREADING

开发者 https://www.devze.com 2023-02-12 12:58 出处:网络
I need a boost thread to report back success or failure. I am currently doing it by passing a pointer to a bool in. It works most ofthe time but throws a access violation error once in a while.

I need a boost thread to report back success or failure. I am currently doing it by passing a pointer to a bool in. It works most of the time but throws a access violation error once in a while.

Is开发者_运维问答 there any thing wrong in passing in pointers for returning success or failure of the thread function ? is there any other way to do this?

BR

Niladri


You may be able to use a future. You can think of a future as a shared value between threads. One thread will write the value of the future and another thread will read it. If the future has not yet been written, the reading thread will block until it has. Futures are already a part of boost.threads.


We can't tell you what is wrong with your code because you haven't posted any of it, but if you are passing in a pointer to your thread function and having your thread assign to it, you need to make sure that memory stays valid throughout the entire duration of your thread.


Most simply, you may just need to wrap your boolean in a class/structure, and protect access to it with a mutex, but I'm not sure an access violation would come from two threads trying to read and write it at the same time:

struct saferBool
{
void setSuccessState ( bool b );
bool wasSuccessful ();
private:
bool successState;
boost::interprocess::interprocess_mutex mutex;
};

void saferBool::setSuccessState ( bool b )
{
mutex.lock();
successState = b;
mutex.unlock();
}

bool saferBool::wasSuccess ()
{
bool b;
mutex.lock();
b = successState;
mutex.unlock();
return b;
}

Otherwise, maybe you're inadvertently change the address pointed to, or the boolean you're pointing to leaves scope in its native thread, making its address invalid for the write by your second thread.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号