Created
November 22, 2012 17:01
-
-
Save ebsaral/4132120 to your computer and use it in GitHub Desktop.
A simple thread example (session control) in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <unistd.h> | |
#include <time.h> | |
#include <pthread.h> // necessary | |
#include <stdlib.h> | |
// Session limit in seconds | |
#define SESSION_TIME 60 | |
// Global last interaction variable | |
time_t lastInteraction; | |
// Thread function that will control session time | |
void * session(void * arg) | |
{ | |
// Session will constantly check if the session is expired or not | |
while(1) | |
{ | |
// In each loop, get current time | |
time_t c; | |
time(&c); | |
// Then compare it with the lastInteraction time | |
if(c - lastInteraction >= SESSION_TIME) | |
{ | |
printf("Session expired\n"); | |
exit(0); | |
} | |
} | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
// Set the initial interaction time | |
time(&lastInteraction); | |
// Create session | |
/* | |
* Note: if pthread_create executes successfuly, tid gets the return id of session. | |
* First NULL indicates we will use default attributes for our thread | |
* session is the name of the method which will handle thread's execution | |
* last NULL is the argument will be used inside session but I preferred using it globally | |
*/ | |
pthread_t tid; | |
pthread_create(&tid, NULL, session, NULL); | |
// Create input string | |
char input[30]; | |
// Program starts | |
while(1) | |
{ | |
// Ask user for inputs with scanf (or fgets depending on your program) | |
// Assume that user waits and does not enter any thing for 60 seconds, | |
// during this time thread gets executed and checks whether the limit is reached or not | |
printf("Enter something: "); | |
input[0] = '\0'; // optional: empty the string | |
scanf("%s", input); | |
// Update the last activation time after user gives an input | |
time(&lastInteraction); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment