Skip to content

Instantly share code, notes, and snippets.

@gnitnaw
Last active October 19, 2016 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gnitnaw/84939b400ba3391cec188e5376dedaf9 to your computer and use it in GitHub Desktop.
Save gnitnaw/84939b400ba3391cec188e5376dedaf9 to your computer and use it in GitHub Desktop.
gcc thread.c -Wall -pedantic -O3 -std=gnu11 -o thread -lpthread
#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