Last active
October 19, 2016 12:39
-
-
Save gnitnaw/84939b400ba3391cec188e5376dedaf9 to your computer and use it in GitHub Desktop.
gcc thread.c -Wall -pedantic -O3 -std=gnu11 -o thread -lpthread
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 <stdatomic.h> | |
#include <pthread.h> | |
typedef struct { | |
char name[16]; | |
int sleepTime; | |
} Node; | |
void _usleep(int); | |
void* generateSingleThread(void*); | |
void printAndSleep(Node*); | |
atomic_int acnt; | |
int main(void) { | |
Node nodes[] = {{"One", 1000}, {"Two", 2000}, {"Three", 3000}}; | |
pthread_t thread[3]; | |
for (int i=0; i<3; ++i) { | |
pthread_create(&thread[i], NULL, generateSingleThread, (void*) &nodes[i]); | |
} | |
for (int i=0; i<3; ++i) pthread_join(thread[i],NULL); | |
return 0; | |
} | |
void* generateSingleThread(void* nodes) { | |
Node* node = (Node*)nodes; | |
for (int i=0; i<10; ++i) { | |
while (acnt) sched_yield() ; | |
++acnt; | |
printf("%dth Time: ", i); | |
--acnt; | |
printAndSleep(node); | |
} | |
pthread_exit(NULL); | |
} | |
void printAndSleep(Node* node) { | |
printf("%s\n", node->name); | |
_usleep(node->sleepTime); | |
} | |
void _usleep(int micro) | |
{ | |
struct timespec req = {0}; | |
req.tv_sec = 0; | |
req.tv_nsec = micro * 1000L; | |
nanosleep(&req, (struct timespec *)NULL); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment