I am very much a novice to C, and I am trying to make a program to run MIDI sequences, and basically, I have two functions, both running a different MIDI pattern, and I need them to run in parallel. Due to the nature of the functions (one running a sequence and the other playing random notes), I am almost 100% sure that I can't have then running in the same function.
I've been scouring the internet for some clue on how to do this with pthreads (which apparently don't work on Windows?) and CreateThread(), but I can't seem to get it to work. I am currently trying to use CreateThread() and trying to bring in the integers required for the random midi sequence and I am getting an error concerning 'LPTHREAD_START_ROUTINE' which reads: 'expected 'LPTHREAD_START_ROUTINE' but argument is of type 'DWORD (*)(int, int, int)'.
A sort of pseudocode of what I'm working on is here:
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
}
Hopefully I have explained my problem well... But I am well aware that the most likely case is that I am going about this CreateThread() thing in all the wrong ways.
Thanks!
The signature of the thread entry function is, from the ThreadProc()
reference page:
DWORD WINAPI ThreadProc(
_In_ LPVOID lpParameter
);
and solo_thread()
does not have that signature.
If it is necessary to supply multiple arguments to the function create a struct
containing multiple members representing the desired arguments. The argument to the thread must outlive the thread otherwise the thread will be accessing a dangling pointer. The common solution is to dynamically allocate the argument and have the thread free()
it when it no longer requires it.
Example:
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);
}