473,837 Members | 1,576 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sleep function and threads

Hi,

I need help witht he sleep function as follows. I need to be write som
code to do the ff:

1. creates a new thread
2. (in the new thread), Sleep for x milliseconds
3. (in the new thread), After time elapsed, call a function via a callback
4. ability to kill the spawned thread.
Pseudocode (from the available docs) is as ff:

//Forward declarations
routine() //sleep is called in here
routine_callbac k() //something to do when times up

void foo( void ) {
if ((h =CreateThread( ..,routine,rout ine_callback,.. &Id.)) {
....
}
.......
//Kill thread
CloseHandle(h) ;
}
I would like a working example that shows me how I can:

1) Specify my routine function
2). Pass a callback function and the sleep time amount to my routine
function
3) Kill the spawned thread.

Many thanks

Nov 17 '05 #1
10 2016
> 1) Specify my routine function

Something like :-

DWORD WINAPI routine( LPVOID lpParameter)
{
//...
}
2). Pass a callback function and the sleep time amount to my routine
function
CreateThread has an LPVOID lpParameter. Pass a pointer to your callback
function as lpParameter.And in your thread proc (routine defined above), you
cast lpParameter back to the function pointer type of your call back
function.
3) Kill the spawned thread.
Just return from the thread proc (in this case, routine defined above)

--
Regards,
Nish [VC++ MVP]
http://www.voidnish.com
http://blog.voidnish.com
"Alfonso Morra" <sw***********@ the-ring.com> wrote in message
news:db******** **@nwrdmz01.dmz .ncs.ea.ibs-infra.bt.com... Hi,

I need help witht he sleep function as follows. I need to be write som
code to do the ff:

1. creates a new thread
2. (in the new thread), Sleep for x milliseconds
3. (in the new thread), After time elapsed, call a function via a callback
4. ability to kill the spawned thread.
Pseudocode (from the available docs) is as ff:

//Forward declarations
routine() //sleep is called in here
routine_callbac k() //something to do when times up

void foo( void ) {
if ((h =CreateThread( ..,routine,rout ine_callback,.. &Id.)) {
....
}
.......
//Kill thread
CloseHandle(h) ;
}
I would like a working example that shows me how I can:

1) Specify my routine function
2). Pass a callback function and the sleep time amount to my routine
function
3) Kill the spawned thread.

Many thanks

Nov 17 '05 #2


Nishant Sivakumar wrote:
1) Specify my routine function

Something like :-

DWORD WINAPI routine( LPVOID lpParameter)
{
//...
}

2). Pass a callback function and the sleep time amount to my routine
function

CreateThread has an LPVOID lpParameter. Pass a pointer to your callback
function as lpParameter.And in your thread proc (routine defined above), you
cast lpParameter back to the function pointer type of your call back
function.


I also need to pass the sleep time. It looks like the CreateProcess API
only expects one parameter to be passed. Does this mean that I have to
wrap both my callback function and sleep time in some kind of ptr to
(user defined parameter) struct or something similar ?
3) Kill the spawned thread.

I want to be able to make the decision to kill the thread from the
Parent thread. Is there anyway to "send messages" (I don't maan WM_*
messages) to the thread?. This will be necesary so that if I move this
code to class fo example, the thread can be killed in the destructor of
the parent that spawned the thread.

Just return from the thread proc (in this case, routine defined above)


Nov 17 '05 #3
> I also need to pass the sleep time. It looks like the CreateProcess API
only expects one parameter to be passed. Does this mean that I have to
wrap both my callback function and sleep time in some kind of ptr to (user
defined parameter) struct or something similar ?
Yep, you can use a struct like :-

struct THREADDATA
{
FUNC_PTR fCallBack;
DWORD dwSlepTime;
};
I want to be able to make the decision to kill the thread from the Parent
thread. Is there anyway to "send messages" (I don't maan WM_* messages) to
the thread?. This will be necesary so that if I move this code to class fo
example, the thread can be killed in the destructor of the parent that
spawned the thread.
Look up PostThreadMessa ge on MSDN.

--
Regards,
Nish [VC++ MVP]
http://www.voidnish.com
http://blog.voidnish.com
"Alfonso Morra" <sw***********@ the-ring.com> wrote in message
news:db******** **@nwrdmz02.dmz .ncs.ea.ibs-infra.bt.com...

Nishant Sivakumar wrote:
1) Specify my routine function

Something like :-

DWORD WINAPI routine( LPVOID lpParameter)
{
//...
}

2). Pass a callback function and the sleep time amount to my routine
function

CreateThread has an LPVOID lpParameter. Pass a pointer to your callback
function as lpParameter.And in your thread proc (routine defined above),
you cast lpParameter back to the function pointer type of your call back
function.


I also need to pass the sleep time. It looks like the CreateProcess API
only expects one parameter to be passed. Does this mean that I have to
wrap both my callback function and sleep time in some kind of ptr to (user
defined parameter) struct or something similar ?
3) Kill the spawned thread.

I want to be able to make the decision to kill the thread from the Parent
thread. Is there anyway to "send messages" (I don't maan WM_* messages) to
the thread?. This will be necesary so that if I move this code to class fo
example, the thread can be killed in the destructor of the parent that
spawned the thread.

Just return from the thread proc (in this case, routine defined above)

Nov 17 '05 #4
Nishant Sivakumar wrote:
I also need to pass the sleep time. It looks like the CreateProcess API
only expects one parameter to be passed. Does this mean that I have to
wrap both my callback function and sleep time in some kind of ptr to (user
defined parameter) struct or something similar ?


Yep, you can use a struct like :-

struct THREADDATA
{
FUNC_PTR fCallBack;
DWORD dwSlepTime;
};


Third member would be a HANDLE to the non-signaled manual reset event
that parent thread sets when it's time for the new thread to finish.

This struct should be created on the heap, so that it still exists when
the new thread begins execution. New thread can delete the struct when
it finishes the execution.

Instead of CreateThread() (not CreateProcess) you may have to use
_beginthreadex( ).
Nov 17 '05 #5


Mihajlo Cvetanović wrote:
Nishant Sivakumar wrote:
I also need to pass the sleep time. It looks like the CreateProcess
API only expects one parameter to be passed. Does this mean that I
have to wrap both my callback function and sleep time in some kind of
ptr to (user defined parameter) struct or something similar ?

Yep, you can use a struct like :-

struct THREADDATA
{
FUNC_PTR fCallBack;
DWORD dwSlepTime;
};

Third member would be a HANDLE to the non-signaled manual reset event
that parent thread sets when it's time for the new thread to finish.


I'm intrigued, please tell me more. How would I set this handle and use
it. i.e. what would I initialize it to and how would I actually use it
inb the code? (a snippet would be useful)
This struct should be created on the heap, so that it still exists when
the new thread begins execution. New thread can delete the struct when
it finishes the execution.
How may I explicitly create a struct on the heap (you're not taling
about global variable declaration here are you?)

Instead of CreateThread() (not CreateProcess) you may have to use
_beginthreadex( ).


Again, a snippet that actually shows how to do this, would be very
useful and much appreciated.

Nov 17 '05 #6
Alfonso Morra wrote:
Hi,

I need help witht he sleep function as follows. I need to be write som
code to do the ff:

1. creates a new thread
2. (in the new thread), Sleep for x milliseconds
3. (in the new thread), After time elapsed, call a function via a callback
4. ability to kill the spawned thread.


Something like this:

#include <process.h>
#include <windows.h>
#include <stdio.h>

struct SleeperThreadDa ta
{
DWORD timeout;
HANDLE endEvent;
void (*callback)(voi d* param);
void* paramValue;
};

unsigned int __stdcall SleeperThreadFu nc(void* param)
{
SleeperThreadDa ta* data = (SleeperThreadD ata*)param;
if (WaitForSingleO bject(data->endEvent, data->timeout) == WAIT_TIMEOUT)
{
//timed out!
(data->callback)(da ta->paramValue);
_endthreadex(0) ;
}
return 1;
}

void callback(void* param)
{
char const* s = (char*) param;
puts(s);
fflush(stdout);
}

int main()
{
HANDLE event = CreateEvent(NUL L, FALSE, FALSE, NULL);
SleeperThreadDa ta threadData = {
2000,
event,
callback,
"Hello World!"
};
unsigned threadID;
HANDLE threadHandle = (HANDLE) _beginthreadex( NULL, 0,
SleeperThreadFu nc, &threadData, 0, &threadID);
WaitForSingleOb ject(threadHand le, INFINITE);
CloseHandle(thr eadHandle);

threadHandle = (HANDLE) _beginthreadex( NULL, 0, SleeperThreadFu nc,
&threadData, 0, &threadID);

Sleep(200);
//fire the event to cancel timeout
SetEvent(event) ;
puts("Cancelled !");
fflush(stdout);
//wait for thread exit
WaitForSingleOb ject(threadHand le, INFINITE);
puts("Thread exited!");
fflush(stdout);
//clean up.
CloseHandle(thr eadHandle);
CloseHandle(eve nt);
}

Obviously, using a nice threading library like boost.threads would make
the code cleaner. In any case, it should all be wrapped into a nice
little library that takes care of the clean up of parameters, etc.

Tom
Nov 17 '05 #7


Tom Widmer [VC++ MVP] wrote:
Alfonso Morra wrote:
Hi,

I need help witht he sleep function as follows. I need to be write som
code to do the ff:

1. creates a new thread
2. (in the new thread), Sleep for x milliseconds
3. (in the new thread), After time elapsed, call a function via a
callback
4. ability to kill the spawned thread.

Something like this:

#include <process.h>
#include <windows.h>
#include <stdio.h>

struct SleeperThreadDa ta
{
DWORD timeout;
HANDLE endEvent;
void (*callback)(voi d* param);
void* paramValue;
};

unsigned int __stdcall SleeperThreadFu nc(void* param)
{
SleeperThreadDa ta* data = (SleeperThreadD ata*)param;
if (WaitForSingleO bject(data->endEvent, data->timeout) == WAIT_TIMEOUT)
{
//timed out!
(data->callback)(da ta->paramValue);
_endthreadex(0) ;
}
return 1;
}

void callback(void* param)
{
char const* s = (char*) param;
puts(s);
fflush(stdout);
}

int main()
{
HANDLE event = CreateEvent(NUL L, FALSE, FALSE, NULL);
SleeperThreadDa ta threadData = {
2000,
event,
callback,
"Hello World!"
};
unsigned threadID;
HANDLE threadHandle = (HANDLE) _beginthreadex( NULL, 0,
SleeperThreadFu nc, &threadData, 0, &threadID);
WaitForSingleOb ject(threadHand le, INFINITE);
CloseHandle(thr eadHandle);

threadHandle = (HANDLE) _beginthreadex( NULL, 0, SleeperThreadFu nc,
&threadData, 0, &threadID);

Sleep(200);
//fire the event to cancel timeout
SetEvent(event) ;
puts("Cancelled !");
fflush(stdout);
//wait for thread exit
WaitForSingleOb ject(threadHand le, INFINITE);
puts("Thread exited!");
fflush(stdout);
//clean up.
CloseHandle(thr eadHandle);
CloseHandle(eve nt);
}

Obviously, using a nice threading library like boost.threads would make
the code cleaner. In any case, it should all be wrapped into a nice
little library that takes care of the clean up of parameters, etc.

Tom


Hi Tom, this is trully wonderful code you have provided. Something I can
really get my teeth stuck into and build on from there. I did want to
use the Boost libararies (because of my cross platform needs) but there
is a section where it (Boost.Threads) mentions potentially non-thread
safe functions - and ctime functions are right in the middle of it. For
now, I will simply expand on the example you kindly provided - as a
proof of concept. If I get stuck, I'll likely come in here again to ask
for more help. Many thanks once again Tom.

Nov 17 '05 #8
Tom Widmer [VC++ MVP] wrote:
HANDLE threadHandle = (HANDLE) _beginthreadex( NULL, 0,
SleeperThreadFu nc, &threadData, 0, &threadID);
WaitForSingleOb ject(threadHand le, INFINITE);
CloseHandle(thr eadHandle);


This is a redundancy, I believe. Instead of these 4 lines there should
be only:

HANDLE threadHandle;

In this example both thread creation and thread abortion are in the same
function, so SleeperThreadDa ta can be created locally. If it were the
case where they are in different functions then this struct should have
been created on the heap:

SleeperThreadDa ta* pThreadData = new SleepThreadData (...);
Nov 17 '05 #9


Alfonso Morra a écrit :
Mihajlo Cvetanović wrote:
Nishant Sivakumar wrote:
I also need to pass the sleep time. It looks like the CreateProcess
API only expects one parameter to be passed. Does this mean that I
have to wrap both my callback function and sleep time in some kind of
ptr to (user defined parameter) struct or something similar ?
Yep, you can use a struct like :-

struct THREADDATA
{
FUNC_PTR fCallBack;
DWORD dwSlepTime;
};

Third member would be a HANDLE to the non-signaled manual reset event
that parent thread sets when it's time for the new thread to finish.


I'm intrigued, please tell me more. How would I set this handle and use
it. i.e. what would I initialize it to and how would I actually use it
inb the code? (a snippet would be useful)

struct THREADDATA
{
FUNC_PTR fCallBack;
DWORD dwSlepTime;
HANDLE hTerminateEvent ;
};

THREADDATA data;
data.hTerminate Event=::CreateE vent(NULL, TRUE, FALSE, NULL); //manual
reset, non signalled event.

See documentation for SetEvent and WaitForSingleOb ject to learn how to
use an event. (in your thread, you should use WaitForSingleOb ject
instead of sleep).

This struct should be created on the heap, so that it still exists when
the new thread begins execution. New thread can delete the struct when
it finishes the execution.


How may I explicitly create a struct on the heap (you're not taling
about global variable declaration here are you?)


THREADDATA* data=new THREADDATA();
//initialize *data fields
//pass data as parameter to CreateThread

At the end of the worker thread, do not forget to delete data.

Instead of CreateThread() (not CreateProcess) you may have to use
_beginthreadex( ).


Again, a snippet that actually shows how to do this, would be very
useful and much appreciated.

RTFM! Look the documentaion for _beginthreadex in MSDN : there is an
example right on the page!

Arnaud
MVP - VC

Nov 17 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1235
by: Mathias Mamsch | last post by:
Hi all, I got a problem with writing a python extension module which launches a bunch of C threads (currently under windows). The module launches a complete speech recognition engine in a new thread and whenever the recognizer recognizes a word a python callback function should be launched. My Problem now is, after dealing with the ThreadState documentation, that in the python test code the interpreter does not return from a time.sleep...
29
3241
by: Jeffrey Maitland | last post by:
Hello all, I am in the process of writing a multithreading program and what I was wondering is a sleep command in an executing function will affect the threads below it? Here is a basic example of what I mean. def main(): temp_var = True while temp_var == True: if
5
23360
by: Parahat Melayev | last post by:
I am trying to writa a multi-client & multi-threaded TCP server. There is a thread pool. Each thread in the pool will handle requests of multiple clients. But here I have a problem. I find a solution but it is not how it must be... i think. When threads working without sleep(1) I can't get response from server but when I put sleep(1) in thread function as you will see in code, everything works fine and server can make echo nearly for...
8
2798
by: Cider123 | last post by:
I ran into a situation where my Window Service had to process 100,000+ files, when I first noticed I needed to tweak various routines. Everything runs fine, but here's what I ran into: In the routine that loops through the file buffer: for (int i=0;i < _Buffer.length; i++) { // Code here
2
500
by: [Yosi] | last post by:
I have C# application, in main form I made thead... User click on susspend button which cause to suspend the thread, in the button fuction: mThread.Susspend(); What I should do to wait in this function untile the thread become susspended ? I tried the following ,but not work I tried Sleep but this cause to sleep all the threads?, why? mThread.Susspend();
3
2125
by: kiplring | last post by:
Suppose a function which has Sleep() method in it. And I want to recycle it. I made two buttons which call "Resume()" and "Suspend()". But It doesn't work. The state of thread "t" will be "WaitSleepJoin" when it runs because the function it calls - "GenerateEvents()" has "Sleep()" function. Can I solve this problem with Thread? I don't want add nasty boll flags on it.
5
3115
by: Sinan Nalkaya | last post by:
hello, i need a function like that, wait 5 seconds: (during wait) do the function but function waits for keyboard input so if you dont enter any it waits forever. i tried time.sleep() but when i used time.sleep in while, the function in while never executed. then i found something about Timer but couldnt realize any algorithm in my mind.
17
6442
by: OlafMeding | last post by:
Below are 2 files that isolate the problem. Note, both programs hang (stop responding) with hyper-threading turned on (a BIOS setting), but work as expected with hyper-threading turned off. Note, the Windows task manager shows 2 CPUs on the Performance tab with hyper-threading is turned on. Both Python 2.3.5 and 2.4.3 (downloaded from python.org) have this problem. The operating system is MS Windows XP Professional.
0
1405
by: Tim Golden | last post by:
Lowell Alleman wrote: Well you've certainly picked a ticklish area to run into problems with ;). First, forget about the threading aspects for the moment. AFAICT the smallest program which reproduces your problem is: <code> import signal
0
9833
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10867
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10562
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10617
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10263
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7803
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5666
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4469
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4036
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.