0

How to block a thread on CPU (So it doesn't use CPU time) and then awaking it after a time t without using signal mechanism.

Abubakr Dar
  • 4,078
  • 4
  • 22
  • 28
Scissor
  • 153
  • 2
  • 14
  • If this is for synchronisation, have you tried using a for loop to make the thread look like it's blocked until a latter time? – Flying_Banana May 13 '15 at 07:14
  • yes , but in that case it'll be consuming cpu and I don't want it to use CPU time. – Scissor May 13 '15 at 07:21
  • Can you expand on your question? What are you trying to achieve? What is your platform? – cnicutar May 13 '15 at 08:04
  • ^^ inter-thread comms is OS-specific. Most relevant OS have events/semaphores, or maybe you can use the POSIX Threads library? – Martin James May 13 '15 at 09:32
  • That's correct @Martin, right now I am using the same approach using POSIX threads and it's working but this implementation require **signaling** and hence not efficient with respect to time. So, I need very fast way ( in ns ). – Scissor May 13 '15 at 09:49
  • I am implementing in Linux system where one thread should block on a variable(no cpu utilization) and other should execute and vice-versa. – Scissor May 13 '15 at 09:52
  • ns, lol, shome joke shurely? – Martin James May 13 '15 at 13:53
  • With general-purpose desktop OS, the best you will be able to do re. latency with kernel inter-thread signaling is a few us. Without kernel signaling, you will burn both CPU and memory-bandwidth on spinlocks. You cannot have both. – Martin James May 13 '15 at 13:59

1 Answers1

0

There is no cross platform way to do this, but a few options are:

Since you are doing this on Linux, your best option is the pthread library and something like pthread_mutex_timedlock

Example:

#include <pthread.h>
#include <time.h>

pthread_mutex_t mutex;
struct timespec timeout;

timeout.tv_sec = 2; // Two seconds
timeout.nv_nsec = 0; // Zero nanoseconds
pthread_mutex_init(&mutex, NULL); // Initialize mutex object
pthread_mutex_timedlock(&mutex, &timeout); // Wait for two seconds.

It is advised you check the return value of the functions for any errors that may have occurred.


If you really don't want to use any OS libraries, you can't put the thread to sleep, but you can use special instructions, such as pause or rep; nop; while spinning to reduce power consumption.

For example:

while (time(NULL) < timeToWake) asm("pause");
mtijanic
  • 2,872
  • 11
  • 26