Reputation: 1432
I'm trying to write a small piece of code that just makes using CreateThread() slightly more clean looking. I can't say that I'm really intending on using it, but I thought it would be a fun, small project for a newer programmer like myself. Here is what I have so far:
#include <iostream>
#include <windows.h>
using namespace std;
void _noarg_thread_create( void(*f)() )
{
cout << "Thread created...\n" << endl;
Sleep(10);
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)f, NULL, 0, NULL);
}
template <typename T>
void _arg_thread_create( void(*f)(T), T* parameter)
{
cout << "Thread created...\n" << endl;
Sleep(10);
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)*f, parameter, 0, NULL);
}
void printnums(int x)
{
for(int i = x; i < 100; i++)
{
cout << i << endl;
}
}
void printnumsnoarg()
{
for(int i = 0; i < 100; i++)
{
cout << i << endl;
}
}
int main()
{
cin.get();
_noarg_thread_create( &printnumsnoarg );
cin.get();
int x = 14;
_arg_thread_create( &printnums, &x );
cin.get();
}
Basically I have two functions that will call two different presets for CreateThread: one for when a parameter is needed in the thread, and one for when no parameter is needed in the thread. I can compile this with the g++ compiler (cygwin), and it runs without any errors. The first thread gets created properly and it prints out the numbers 0-99 as expected. However, the second thread does not print out any numbers (with this code, it should print 14-99). My output looks like this:
<start of output>
$ ./a.exe
Thread created...
0
1
2
3
.
.
.
97
98
99
Thread Created...
<end of output>
Any ideas why the second thread isn't working right?
Upvotes: 1
Views: 131
Reputation: 10377
you actually seem to miss you're passing a pointer to your printnums(int x)
function. As the storage location of x
in your main function will be a lot bigger than 100 your loop never runs.
You should try to change printnums
to:
void printnums(int *x)
{
for(int i = *x; i < 100; i++)
{
cout << i << endl;
}
}
I guess everything will work as expected then.
Upvotes: 1