相关疑难解决方法(0)

我什么时候应该使用std :: thread :: detach?

有时我必须使用它std::thread来加速我的应用程序.我也知道join()等待线程完成.这很容易理解,但是呼叫detach()和不呼叫之间的区别是什么?

我认为没有detach(),线程的方法将独立使用线程.

不分离:

void Someclass::Somefunction() {
    //...

    std::thread t([ ] {
        printf("thread called without detach");
    });

    //some code here
}
Run Code Online (Sandbox Code Playgroud)

呼叫分离:

void Someclass::Somefunction() {
    //...

    std::thread t([ ] {
        printf("thread called with detach");
    });

    t.detach();

    //some code here
}
Run Code Online (Sandbox Code Playgroud)

c++ c++11 stdthread

124
推荐指数
4
解决办法
7万
查看次数

为什么`std :: exit`不会按预期触发析构函数?

#include <cstdlib>
#include <thread>
#include <chrono>
#include <iostream>

using namespace std;
using namespace std::literals;

struct A
{
    int n_ = 0;
    A(int n) : n_(n) { cout << "A:" << n_ << endl; }
    ~A() { cout << "~A:" << n_ << endl; }
};

A a1(1);

int main()
{
    std::thread([]()
    {
        static A a2(2);
        thread_local A a3(3);
        std::this_thread::sleep_for(24h);
    }).detach();

    static A a4(4);
    thread_local A a5(5);

    std::this_thread::sleep_for(1s);
    std::exit(0);
}
Run Code Online (Sandbox Code Playgroud)

我的编译器是clang 5.0-std=c++1z.

输出如下:

A:1
A:2
A:4
A:5 …
Run Code Online (Sandbox Code Playgroud)

c++ destructor global-variables thread-local-storage c++11

24
推荐指数
2
解决办法
2687
查看次数

当父线程终止时,子线程是否退出

我正在使用调用beginthreadex,endthreadex在Visual Studio C++中进行一些多线程编程.

我创建了一个子线程thread1.子线程运行在一个永不退出的函数上,因为它具有无限循环.现在,如果父线程因错误终止或成功完成,子线程是否也会退出?我的疑问是 - 即使在主程序退出后,是否存在子线程仍处于活动状态的情况?

对于linux,这种情况应该怎样?

c++ windows

22
推荐指数
2
解决办法
3万
查看次数

从main调用pthread_exit可以吗?

当我打电话pthread_exitmain,程序永远不会终止.我期望程序完成,因为我退出程序的唯一线程,但它不起作用.好像挂了.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int main(int argc, char *argv[])
{
    printf("-one-\n");

    pthread_exit(NULL);

    printf("-two-\n");
}
Run Code Online (Sandbox Code Playgroud)

Process Explorer显示(仅)线程处于Wait:DelayExecution状态.

根据pthread_exit文件:

在最后一个线程终止后,进程将以退出状态0退出.行为应该就像实现在线程终止时调用带有零参数的exit()一样.

我正在使用Dev-C++ v4.9.9.2pthreads-win32 v2.8.0.0(链接libpthreadGC2.a).

该库似乎是确定(例如,呼叫pthread_selfpthread_createmain正常工作).

是否有什么我不应该调用任何理由pthread_exitmain

c winapi program-entry-point pthreads exit

13
推荐指数
2
解决办法
1万
查看次数

将信号(SIGINT)传播到C++ 11线程

我试图在收到SIGINT信号时正确地终止我的多线程C++ 11应用程序(^C它是),但由于某种原因它不会传播到子线程,尽管主线程很好地响应它.

对于instnce(如下面的代码示例中所示),如果我们在线程内部有一些阻塞函数(例如sleep()),^C如果你使用比如安装任何SIGNT钩子,它将取消你的所有控制权sigaction().

有没有办法解决或解决这种行为?有没有办法将主接收信号传播到子线程?

编辑:sleep()用C++ 11 替换POSIXstd::this_thread::sleep_for()

#include <iostream>
#include <thread>
#include <chrono>
#include <signal.h> // for sigaction() function 

static int signaled = 0;

void threaded_foo() {
  while (!signaled) {
    // pressing ^C now will not lead to correct termination, because we are
    // sleeping for a long time (100500 seconds) and do not respond to
    // SIGINT for some tricky reason i am looking a bypassage for. …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading signals c++11

7
推荐指数
1
解决办法
1万
查看次数

是否有可能获得主线程的线程对象,以及`join()`?

有没有办法像使用C++ 11(或更高版本)工具的任何其他线程一样处理主线程?具体来说,我正在寻找能够join()与主线程.所以,基本上,我想做类似的事情main_thread.join(),但不知道如何获取main_thread对象.

线程构造函数似乎没有提供任何基于例如获得的线程id的工具get_id().该this_thread命名空间还只提供最低限度的功能,但是偏出例如join(),这正是我所期待的.

c++ multithreading c++11

5
推荐指数
1
解决办法
254
查看次数

在stdin阻塞Windows时退出应用程序

我有一个应用程序,它使用线程中的getline()从标准输入读取数据.我想从主线程关闭应用程序,而getline仍然阻止其他线程.怎么能实现这一目标?

我不想强迫用户必须按ctrl-Z来关闭stdin和应用程序.

到目前为止,我已尝试使用Windows 8.1 64bit,v120平台工具集上的编译器设置(RuntimeLibrary =/MT):

  • freopen stdin,但它被内部锁定阻止
  • 破坏线程,调用abort()
  • 将一个Eof,行结尾放到std :: cin,它也被阻止了

*更新*

  • detach()不起作用,exit()被锁定阻止
  • winapi TerminatThread()调用abort()
  • winapi CloseHandle(GetStdHandle(STD_INPUT_HANDLE))挂起
  • 调用TerminateProcess() - 有效,但我想优雅地退出

*更新2:解决方案*

  • WriteConsoleInput()可以使std :: getline()从阻塞读取返回.这适用于任何msvc运行时库.对于工作解决方案的代码,请参见已接受

显示问题的示例代码:

#include <iostream>
#include <thread>
#include <string>
#include <chrono>

int main(int argc, char *argv[])
{
    bool stop = false;
    std::thread *t = new std::thread([&]{
        std::string line;
        while (!stop && std::getline(std::cin, line, '\n')) {
            std::cout << line;
        }
    });

    std::this_thread::sleep_for(std::chrono::seconds(1));

    stop = true;
    // how to stop thread or make getline to return here?

    return 0; …
Run Code Online (Sandbox Code Playgroud)

windows multithreading stdin c++11 msvc12

5
推荐指数
1
解决办法
759
查看次数

执行异步作业的函数

我有函数foo:

void foo(){
    //Command set A
    std::this_thread::sleep_for(100s);
    //Command set B
}
Run Code Online (Sandbox Code Playgroud)

第一部分是Command set A必须阻止执行.但是,该sleep部分并//Command set B不必阻止执行,也不会返回任何数据.

所以我实现如下:

void foo(){
    //Command set A
    std::thread t([](){
        std::this_thread::sleep_for(100s);
        //Command set B
    }
    t.detach()
}
Run Code Online (Sandbox Code Playgroud)

detach在这里使用得当吗?它是正确的使用场所detach吗?有更好的解决方案吗?

c++ multithreading detach

1
推荐指数
1
解决办法
67
查看次数

为什么Win api线程执行函数,而标准线程不执行函数?

我有15个线程,我想执行10个推入的函数。我现在不在乎保护它,只是想知道为什么win api会执行功能,而std不会。

编码从手工制作的英雄日123开始或多或少

struct WorkQueueEntry
{
    char* stringToPrint;
};
static uint32 nextEntryToDo;
static uint32 entryCount;
WorkQueueEntry entries[256];

inline void PushString(const char* string)
{
    WorkQueueEntry* entry = entries + entryCount++;
    entry->stringToPrint = const_cast<char*>(string);
}

struct ThreadInfo
{
    int logicalThreadIndex;
};

DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
    printf("entry count %i, nextEntryToDo %i\n", entryCount, nextEntryToDo);
    ThreadInfo* threadInfo = (ThreadInfo*)lpParameter;
    for(;;) {
        if(nextEntryToDo < entryCount) {
            WorkQueueEntry* entry = entries + nextEntryToDo++;
            char buffer[256];
            sprintf_s(buffer, "Thread %u: %s", threadInfo->logicalThreadIndex, entry->stringToPrint);
            printf(buffer);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在主要的某个地方 …

c++ winapi multithreading std

0
推荐指数
1
解决办法
79
查看次数

Start thread within member function using std::thread &amp; std::bind

I have few queries with respect to below code snapshot.

1) With respect to pthread_create(), assume Thread_1 creates Thread_2. To my understanding Thread_1 can exit without join, but still Thread_2 will keep running. Where as in below example without join() I am not able to run thread and I am seeing exceptions.

2) In few examples I am seeing thread creation without thread object as below. But when I do the same, code is terminated.

std::thread(&Task::executeThread, this);

I am compiling …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading c++11

0
推荐指数
1
解决办法
88
查看次数