使用CreateThread()在C中进行线程化

时间:2013-05-09 13:06:47

标签: c windows multithreading winapi createthread

我非常喜欢C,我正在尝试制作一个程序来运行MIDI序列,基本上,我有两个函数,都运行不同的MIDI模式,我需要它们并行运行。由于功能的性质(一个运行序列而另一个运行随机音符),我几乎100%确定我不能再运行相同的功能。

我一直在网上寻找一些关于如何使用pthreads(显然在Windows上不起作用?)和CreateThread()的方法,但我似乎无法让它工作。我目前正在尝试使用CreateThread()并尝试引入随机midi序列所需的整数,并且我收到有关'LPTHREAD_START_ROUTINE'的错误,其中显示为:'expected'LTTHREAD_START_ROUTINE'但参数类型为'DWORD(*) (int,int,int)'。

我正在处理的一种伪代码在这里:

DWORD WINAPI solo_thread(int key, int tempo, int scale)
{
                  ///// this contains the random midi notes
}
int backing(int key, int tempo, int backing)
{
    HANDLE thread = CreateThread(NULL, 0, solo_thread, NULL, 0, NULL);
    if (thread) {
                 ////// this contains the midi sequence

}

希望我已经很好地解释了我的问题......但我很清楚最可能的情况是我会以错误的方式处理这个C​​reateThread()事情。

谢谢!

1 个答案:

答案 0 :(得分:3)

线程录入功能的签名来自ThreadProc()参考页面:

DWORD WINAPI ThreadProc(
  _In_  LPVOID lpParameter
);

solo_thread()没有该签名。

如果需要为函数提供多个参数,请创建一个struct,其中包含表示所需参数的多个成员。线程的参数必须比线程更长,否则线程将访问悬空指针。常见的解决方案是动态分配参数,并在不再需要时使用线程free()

示例:

struct Thread_data
{
    int key;
    int tempo;
    int scale;
};

DWORD WINAPI solo_thread(void* arg)
{
    struct Thread_data* data = arg;

    /* Use 'data'. */

    free(data);
    return 0;
}

int backing(int key, int tempo, int backing)
{
    struct Thread_data* data = malloc(*data);
    if (data)
    {
        data->key   = key;
        data->tempo = tempo;
        data->scale = backing;
        HANDLE thread = CreateThread(NULL, 0, solo_thread, &data, 0, NULL);
    }