我是 C 的新手,我正在尝试编写一个程序来运行 MIDI 序列,基本上,我有两个函数,都运行不同的 MIDI 模式,我需要它们并行运行。由于函数的性质(一个运行序列,另一个播放随机音符),我几乎 100% 确定我不能在同一函数中运行。
我一直在互联网上搜索有关如何使用 pthread(这显然在 Windows 上不起作用?)和 CreateThread() 执行此操作的线索,但我似乎无法让它工作。我目前正在尝试使用 CreateThread() 并尝试引入随机 midi 序列所需的整数,但我收到有关“LPTHREAD_START_ROUTINE”的错误,内容为:“预期的‘LPTHREAD_START_ROUTINE’,但参数类型为‘DWORD (*) (整数,整数,整数)'。
这里是我正在处理的一种伪代码:
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
}
希望我已经很好地解释了我的问题......但我很清楚最有可能的情况是我正在以所有错误的方式处理这个 CreateThread() 事情。
谢谢!
最佳答案
线程入口函数的签名是,来自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);
}
关于c - 使用 CreateThread() 在 C 中线程化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16462580/