dev/cpp/multithreading/pthread_ex.c

61 lines
982 B
C

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
static void wait_thread(void)
{
time_t start_time = time(NULL);
while (time(NULL) == start_time)
{
/* do nothing except chew CPU slices for up to one second. */
usleep(10000);
//~ struct timespec ts;
//~ ts.tv_sec = 0;
//~ ts.tv_nsec = 1000;
//~ nanosleep((const struct timespec *)&ts, NULL);
}
}
static void *thread_func(void *vptr_args)
{
int i;
for (i = 0; i < 10; i++)
{
fputs(" b\n", stderr);
wait_thread();
}
return NULL;
}
int main(void)
{
int i;
pthread_t thread;
if (pthread_create(&thread, NULL, thread_func, NULL) != 0)
{
return EXIT_FAILURE;
}
for (i = 0; i < 10; i++)
{
puts("a");
wait_thread();
}
if (pthread_join(thread, NULL) != 0)
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}