2013-09-23 49 views
1
class Class { 
public: 
    Class(); 
private: 
    std::thread* updationThread; 
}; 

构造:暂停的std ::线程,直到功能完成

Class::Class() { 
    updationThread = new std::thread(&someFunc); 
} 

在我的应用程序的某个时刻,我必须暂停该线程和调用函数和函数我要执行后恢复线程。比方说,它发生在这里:

void Class::aFunction() { 
    functionToBeCalled(); //Before this, the thread should be paused 
    //Now, the thread should be resumed. 
} 

我曾尝试使用另一个线程与功能functionToBeCalled()和使用thread::join,但无法做到,由于某种原因。

如何暂停一个线程或者我如何使用thread::join暂停线程,直到其他完成?

+0

那是什么其他的线程在做什么?你可以玩“someFunc”的身体吗? “暂停”线程不是正常操作。 – user7116

+0

STL不提供此。在Windows中,您可以使用SuspendThread。 – cdoubleplusgood

+0

@ user7116我可以。我想这样做的原因是因为当'functionToBeCalled()'和线程一起工作时,我遇到了内部问题。 – khajvah

回答

4

我不认为你可以很容易地(以标准的方式)“暂停”某个线程,然后恢复它。我想你可以发送SIGSTOP和SIGCONT如果你是使用一些Unix味的操作系统,但除此之外,你应该正确标注内someFunc()原子零件与互斥和锁,一个包裹functionToBeCalled()与相应的互斥锁:

std::mutex m; // Global mutex, you should find a better place to put it 
       // (possibly in your object) 

,并在函数内部:

void someFunc() { 
    // I am just making up stuff here 
    while(...) { 
     func1(); 

     { 
      std::lock_guard<std::mutex> lock(m); // lock the mutex 
      ...; // Stuff that must not run with functionToBeCalled() 
     } // Mutex unlocked here, by end of scope 
    } 
} 

,并呼吁functionToBeCalled()时:

void Class::aFunction() { 
    std::lock_guard<std::mutex> lock(m); // lock the mutex 
    functionToBeCalled(); 
} // Mutex unlocked here, by end of scope 
+0

更重要的是,*你不想“暂停”*。如果'B'在B运行时不能运行,它们必须共享一些数据依赖。简单地暂停执行'A'的线程并不能保证当'A'处于适当和/或一致的状态w'r.t时'B'将运行。数据依赖性(即保护处理共享数据的部分是正确答案)。 – user7116

+0

@ user7116当文件被修改时,我的线程很简单地捕获信号。我用它来知道文件在应用程序外部何时被修改。该功能修改文件。它写入一些文件并在写入第一个字符串之后,线程工作并且应用程序崩溃,因为函数不会将所有内容写入文件 – khajvah

+0

@ user7116当文件写入所有内容时,我不认为崩溃会发生。 – khajvah