createthread()如何更好地释放内存?

时间:2016-09-16 03:04:50

标签: c++ windows winapi

我想在createthread()之后关闭一个线程并释放内存。我通过返回createthread()的回调和closehandle()来完成此操作。有人说这不能释放记忆清晰。我正在测试它,到目前为止,这么好。它看起来不错?

我拿了一面旗子:endThread这样做,有太多的旗帜,太多了,如果,看起来很难看,怎么做得更好?

typedef void(*pfunc)(char*);
HANDLE H_thread=NULL;
int endThread = 0;//0:thread not start;1:end thread order;2:thread started
void mycall(char*s){
    cout << "callback" << endl;
    cout << s << endl;
}
static DWORD WINAPI myfunc(LPVOID lp)
{
    while (1)
    {
        ((pfunc)lp)("2222");
        cout << "thread..........." << endl;
        Sleep(10);
        if (1==endThread)
        {
            endThread = 0;
            return 0;
        }
    }
}
void thread_callback(pfunc call){
    if (0==endThread)
    {
        H_thread = CreateThread(NULL, 0, myfunc, call, 0, NULL);
        endThread = 2;
        call("1111");
    }
}
int _tmain(int argc, _TCHAR* argv[])
{
    while (true)
    {
        thread_callback(mycall);
        endThread = 1;
        //wait for thread end.
        while (endThread != 0){
            Sleep(1);
        }
        CloseHandle(H_thread);
        H_thread = NULL;
    }
    while(1);
    return 0;
}

1 个答案:

答案 0 :(得分:1)

您正在反复创建和销毁线程。它甚至不检查线程是否完成。这不是你的目标。使用WaitForSingleObjectWaitForMultipleObjects确保线程已完成。在Window程序(不是控制台)中,您可以使用SendMessage从线程到GUI线程,以指示线程已完成。

尝试以下示例。此外,您可以使用system("pause");代替while(1);,但只有在调试模式下从VS IDE运行程序时才需要这样做。另见MSDN example

#include <iostream>
#include <string>
#include <windows.h>

struct T_data {
    std::wstring text;
};

DWORD WINAPI thread_function(void *ptr) {
    T_data* data = (T_data*)ptr;
    MessageBoxW(GetConsoleWindow(), data->text.c_str(), 0, 0);
    return 0;
}

int main() {
    T_data *data = new T_data;
    data->text = L"hello world";
    DWORD threadId;
    HANDLE handle = CreateThread(NULL, 0, thread_function, data, 0, &threadId);

    if (handle) {
        printf("thread started\n");
        while (WaitForSingleObject(handle, 100))
            printf(".");
        printf("\nthread finished\n");
        CloseHandle(handle);
    }

    delete data;
    system("pause");
    return 0;
}

如果共享数据,删除数据可能会变得棘手,具体取决于您希望在何处以及如何执行此操作。调用线程可以在接收线程完成处理之前删除数据。由于您未在问题中显示任何此类共享数据,因此我将其排除在外。