Well, I got this answer for my explanation....
I asked:
Could anyone briefly tell how to create a multithreading in windows C for the below problem...
Code:
typedef struct tagCON {
BOOL fTimeout;
SEARCH_STATUS ss;
} CON, *PCON
int main()
{
char line[256], command[256];
static CON s_con;
PCON pcon = &s_con;
for(;;)
{
if(!fgets(line, 256, stdin))
return;
sscanf(line, "%s", command);
if(!strcmp(command, "go") {
think(pcon);
continue;
}
if(!strcmp(command, "quit") {
pcon->fTimeout = TRUE;
continue;
}
So I am calling think() from main and also passing a struct object. think() is basically executing for more than 10 mins...
What I want is, whenever user enters "quit", fTimeout is set to true, and inside think() for every millisec I am checking if fTimeout is true and if so, I will return to main.
But the problem is, since control is passed to think() from main, fgets() is not getting user input until control from think() is returned back to main. So how this can be achieved please?
Thanks in advance.
Someone replied
I don't think that you need threading for this. This is simple case when user waits for execution and optionally stops it - for such case, it is enough to test pressed key periodically. You can print something like this:
printf("Press Esc to stop\n");
think(...);
Inside think function, add the following code:
Code:
while (...) // some loop - I guess you have it
{
// calculations
// ...
if ( _getch() == 27 ) // Esc ?
return;
}
I asked:
Well but I am not inputting them through keyboard.. There is a GUI interface through which commands like "quit", "go" etc are sent...
So I doubt, if I use _getch() inside think() will fetch the commands sent by GUI ?
Only in main() I can get right ?
Someone replied:
Is this console application or Winnows application? Looking at your main function I guess that this is console application. Do you have message loop?
I asked:
I am really sorry... I made a small mistake. Just replace that main() with xboard().
main() calls the above xboard(pcon).
ok?
Someone replied:
There are better ways to design the flow but.. you can just create a thread on yout think() function as follows:
Code:
void
think(PVOID pArg){
while (1) {
PCON pCon = (PCON)pArg;
// keep think...ing...
if (timeoutSet){
ExitThread()
}
}
}
main(){
for (;;;){
// populate a new struct arg from command fgets()..
PCON pCon = new CON;
If (command != "quit"){
DWORD Id;
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE )think, pCon, 0, &Id);
} else {
// set timeout flag
// cleanup
// break;
}
}
// what else to do ?
}
Since the above is in another forum, I am not refering that link because I dont know if its legal as per the rules of this forum. Thanks.