c++ - p_thread : exit from multiple threads

标签 c++ multithreading pthreads exit

我在程序中创建了两个线程。我想根据标志终止 thread_2 函数内的 thread_1,反之亦然。我尝试了 exit() 和 pthread_exit(Thread_id) 但它不起作用。我想通过调用 pthread_cancel 来取消线程执行,但问题是我无法在 pthread_create 之前传递线程 ID。有什么建议吗??

最佳答案

你可以看到pthread_cancel是如何工作的in the manpage .

不过,既然提到了C++,为什么不用语言特性呢?可以使用条件变量向一个或多个其他线程发送信号。

查看 Live On Coliru

如果您没有 C++11,您可以使用 Boost Threads。

#include <thread>
#include <condition_variable>
#include <iostream>

using namespace std;

struct workers
{
    mutex mx;
    condition_variable cv;
    bool canceled;

    workers() : canceled(false) {}

    void thread1()
    {
        cout << __PRETTY_FUNCTION__ << " start\n";
        this_thread::sleep_for(chrono::seconds(2));

        {
            unique_lock<mutex> lk(mx);
            cout << __PRETTY_FUNCTION__ << " signaling cancel\n";
            canceled = true;
            cv.notify_all();
        }

        this_thread::sleep_for(chrono::seconds(2));
        cout << __PRETTY_FUNCTION__ << " done\n";
    }

    void thread2()
    {
        cout << __PRETTY_FUNCTION__ << " start\n";

        for(;;)
        {
            // do some work
            unique_lock<mutex> lk(mx);
            if (cv.wait_for(lk, chrono::milliseconds(10), [this] { return canceled; }))
                break;
        }

        cout << __PRETTY_FUNCTION__ << " done\n";
    }
};

int main()
{
    workers demo;
    std::thread t1(&workers::thread1, ref(demo));
    std::thread t2(&workers::thread2, ref(demo));

    t1.join();
    t2.join();
}

输出:

void workers::thread1() start
void workers::thread2() start
void workers::thread1() signaling cancel
void workers::thread2() done
void workers::thread1() done

更新 带boost的C++03版本是 Live On Coliru 现在也是。为了好玩,我添加了时间戳:

thread1:21 2014-Mar-26 00:01:40.074269 start
thread2:37 2014-Mar-26 00:01:40.074275 start
thread1:26 2014-Mar-26 00:01:42.074873 signaling cancel
thread2:47 2014-Mar-26 00:01:42.074991 done
thread1:32 2014-Mar-26 00:01:44.075062 done

关于c++ - p_thread : exit from multiple threads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22648567/

相关文章:

multithreading - 双核cpu上的多线程

c - Pthreads - 高内存使用率

c++ - 编译器 `constexpr` 一切吗?

c++ - 在 ARM 平板电脑上编程

python - 套接字和线程python

multithreading - 当线程被调度到不同的 CPU 内核上时,预期的内存语义(例如先读后写)会发生什么?

c++ - 在调用者的堆栈上分配内存

c++ - 基类函数成员在派生类对象上执行只有一种情况

linux - Linux 中进程的线程堆栈

c++ - 等效于 Linux 上的 SetThreadPriority (pthreads)