Note that there are some explanatory texts on larger screens.

plurals
  1. POThread timer in c
    primarykey
    data
    text
    <p>can someone help me to transform my code to a working code :</p> <pre><code>#include &lt;pthread.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /* call back function - inform the user the time has expired */ void timeout_call_back() { printf("=== your time is up ===\n"); // doing some other stuff } /* Go to sleep for a period of seconds */ static void* start_timer(void *args) { /* function pointer */ void (*finish_function)(); int seconds = *((int*) args); pthread_mutex_lock(&amp;mutex); // I want to do this action atomically printf("thread ID : %ld, go to sleep for %d\n", pthread_self(), seconds); finish_function = timeout_call_back; // ATOMIC PART // This function is called in real time, so I need it // to be safe, and it's executed just when the timer is not reached. atomic_function_callback(); // THIS IS MY PROBLEM. I WANT TO WAIT for (seconds) seconds, // but I don't want to block other threads. sleep(seconds); /* call the cb to inform the user time is out */ (*finish_function)(); pthread_mutex_unlock(&amp;mutex); pthread_exit(NULL); } int main() { pthread_t thread1, thread2, thread3; int seconds1 = 300; int seconds2 = 600; int seconds3 = 900; int rc1, rc2, rc3; rc1 = pthread_create(&amp;thread1, NULL, start_timer, (void *) &amp;seconds1); if(rc1) printf("=== Failed to create thread1\n"); rc2 = pthread_create(&amp;thread2, NULL, start_timer, (void *) &amp;seconds2); if(rc2) printf("=== Failed to create thread2\n"); rc3 = pthread_create(&amp;thread3, NULL, start_timer, (void *) &amp;seconds3); if(rc3) printf("=== Failed to create thread3\n"); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); printf("=== End of all threads in ===\n"); return 0; } </code></pre> <p>When i run this code just one thread can run in a time (cause of mutex) but i need this mutex. is there any alternative to sleep() that allow me to do a non blocking timer?</p> <p>This is just a sample, my real timers are very long (8 hours).</p> <p>Thanks.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload