Skip to content

Instantly share code, notes, and snippets.

@shonenada
Created June 25, 2014 07:06
Show Gist options
  • Save shonenada/d45b65e5c61f5c1197c2 to your computer and use it in GitHub Desktop.
Save shonenada/d45b65e5c61f5c1197c2 to your computer and use it in GitHub Desktop.
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
void* thread_function(void *arg);
int run_row = 1;
pthread_mutex_t work_mutex;
int main() {
int print_count = 0;
pthread_t a_thread;
if (pthread_mutex_init(&work_mutex, NULL) != 0) {
perror("Mutex init failed\n");
exit(1);
}
if (pthread_create(&a_thread, NULL, thread_function, NULL) != 0) {
perror("Thread creation failed\n");
exit(1);
}
if (pthread_mutex_lock(&work_mutex) != 0) {
perror("Lock failed\n");
exit(1);
} else {
printf("Main Lock!\n");
}
while (print_count++ < 5) {
if (run_row == 1) {
printf("Main thread is running\n");
run_row = 2;
} else {
printf("Main thread is sleep\n");
sleep(1);
}
}
if (pthread_mutex_unlock(&work_mutex) != 0) {
perror("unlock failed\n");
exit(1);
} else {
printf("Main unlock\n");
}
pthread_join(a_thread, NULL);
pthread_mutex_destroy(&work_mutex);
exit(0);
}
void *thread_function(void *arg) {
int print_count = 0;
if (pthread_mutex_lock(&work_mutex) != 0) {
perror("Thread Lock failed\n");
exit(1);
} else {
printf("Function Lock!\n");
}
while(print_count++ < 5) {
if (run_row == 2) {
printf("function thread is running\n");
run_row = 1;
} else {
printf("function thread is sleep\n");
sleep(1);
}
}
if (pthread_mutex_unlock(&work_mutex) != 0) {
perror("Thread unlock failed\n");
exit(1);
} else {
printf("Function unlock!\n");
}
pthread_exit(NULL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment