1

我在 C++ 中使用以下线程来检查是否满足某个条件,如果满足,那么它应该打破循环。我在一个while循环中调用线程,所以我需要它来中断。刷新令牌由另一个线程更新。

void ThreadCheck( void* pParams )
{
  if(refresh)
  {
      continue;
  }
 }

我的while循环:-

while(crun)
{
    refresh = false;
    _beginthread( ThreadCheck, 0, NULL );
    rlutil::setColor(8);
    cout<<"Send>> ";
    getline(cin, msg); //Make a custom function of this.
    if(stricmp(msg.c_str(), "exit")==0)
    { 
        crun = false;
    }
    else if(msg.empty() || stricmp(msg.c_str()," ")==0)
    {
       rlutil::setColor(4);
       cout<<"Plz enter a valid message!\n";

       continue;

    } else {
    manager('c', msg);
    // msg.append("\n");
    // chat_out<<msg;
    // chat_out.close();
        }
    cout<<"\n";
}
4

2 回答 2

3

当另一个线程正在或可能正在访问它时,您不能修改一个线程中的值。您需要使用某种形式的同步,例如锁。

于 2013-09-09T08:39:42.380 回答
1

您有 2 个线程:1) 主线程,2) ThreadCheck。添加一个互斥锁,以免同时更新'crun',并且在线程内部将值更新为false。而已

#include <iostream>
#include "/tbb/mutex.h"
#include "/tbb/tbb_thread.h"
using namespace tbb;

typedef mutex myMutex;
static myMutex sm;
int i = 0;

void ThreadCheck( ) 
{ 
      myMutex::scoped_lock lock;//create a lock
      lock.acquire(sm);//Method acquire waits until it can acquire a lock on the mutex
         //***only one thread can access the lines from here...***
        crun = false;;//update is safe (only one thread can execute the code in this scope) because the mutex locked above protects all lines of code until the lock release.
         sleep(1);//simply creating a delay to show that no other thread can update 
         std::cout<<"ThreadCheck "<<"\n";
         //***...to here***

      lock.release();//releases the lock (duh!)      
}

int main()
{
   tbb_thread my_thread(ThreadCheck);//create a thread which executes 'someFunction'

   // ... your code

   my_thread.join();//This command causes the main thread (which is the 'calling-thread' in this case) to wait until thread1 completes its task.

}
于 2013-09-09T08:45:56.747 回答