/* spin.c
----------
C
multi-threaded
reader-writer threads
atomic
RCU
pointer
SMP/multi-processor/multi-core
spinlock
non-blocking
code requires posix threads (pthreads) dev package
build with:
gcc spin.c -Wall -Wextra -O3 -lpthread
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/* a global pointer, accessible by both threads: */
char * volatile test = 0;
/* the writer thread: */
void* thread_func(void* ptr)
{
struct timespec req = { .tv_sec = 2, .tv_nsec = 0 };
struct timespec rem = { 0, 0 };
test = strdup(*((char**)ptr));
nanosleep(&req, &rem);
test = strdup("Hello!");
nanosleep(&req, &rem);
test = strdup("Goodbye!");
nanosleep(&req, &rem);
test = 0;
nanosleep(&req, &rem);
test = strdup("Computation complete.");
return 0;
}
int main()
{
char* ick = "Computing...";
char* test_old = 0;
char* test_to_free = 0;
pthread_attr_t attr;
pthread_t pth;
struct timespec req = { .tv_sec = 0, .tv_nsec = 100000 };
struct timespec rem = { 0, 0 };
/* setup writer thread attributes: */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
/* spawn writer thread: */
if (pthread_create(&pth, &attr, thread_func, &ick))
{
fprintf(stderr, "Failed to create thread\n");
return 0;
}
/* just pause a moment and collect our thoughts: */
nanosleep(&req, &rem);
/* reader: */
test_old = test;
do
{
printf("%s \n", test);
int i = 12500;
do
{
nanosleep(&req, &rem);
printf("%08d\033[A\n", --i);
}
while(test == test_old);
test_to_free = test_old;
test_old = test;
free(test_to_free);
}
while(test);
puts(" ");
/* wait for writer thread to finish:*/
pthread_join(pth, 0);
printf("%s\n", test);
free(test_old);
free(test);
return 0;
}
_______________________________________________
NetBehaviour mailing list
[email protected]
http://www.netbehaviour.org/mailman/listinfo/netbehaviour