Skip to content

Instantly share code, notes, and snippets.

@moiz-frost
Created April 28, 2017 14:43
Show Gist options
  • Save moiz-frost/9a3f9f60828d6d795ddacdc3ab15b470 to your computer and use it in GitHub Desktop.
Save moiz-frost/9a3f9f60828d6d795ddacdc3ab15b470 to your computer and use it in GitHub Desktop.
pthread + cancel + mutex
// Run 'gcc -pthread pthread.c -o exec' to compile
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#define LINE_READ_SIZE 100
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_t ThreadOne; // thread ID
pthread_t ThreadTwo; // thread ID
int sharedInteger;
static void sigint_handler (int signo)
{
pthread_cancel(ThreadOne);
write(STDOUT_FILENO, "\n ThreadOne Cancelled", sizeof("\n ThreadOne Cancelled"));
// exit (EXIT_SUCCESS);
}
void *threadOne()
{
pthread_mutex_lock (&mutex);
write(STDOUT_FILENO, "\nIn ThreadOne", sizeof("\nIn ThreadOne"));
while(1)
{
sharedInteger++;
printf("\n%d ThreadOne", sharedInteger);
}
pthread_exit(0);
}
void *threadTwo()
{
pthread_mutex_lock (&mutex);
write(STDOUT_FILENO, "\nIn ThrexadTwo", sizeof("\nIn ThreadTwo"));
while(1)
{
sharedInteger++;
printf("\n%d ThreadTwo", sharedInteger);
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
if (signal (SIGINT, sigint_handler) == SIG_ERR) {
fprintf (stderr, "Cannot handle SIGINT!\n");
exit (EXIT_FAILURE);
}
int lockedThreadReturnValue = pthread_create(&ThreadOne, NULL, threadOne, NULL); // create a thread task
int otherThreadReturnValue = pthread_create(&ThreadTwo, NULL, threadTwo, NULL); // create a thread task
// Do some other work while thread is executing
// sleep(2);
write(STDOUT_FILENO, "Doing some other work...\n", sizeof("Doing some other work...\n"));
// Finish doing some other work
if(ThreadOne < 0)
{
perror("lockedThread Error");
}
if(ThreadTwo < 0)
{
perror("otherThreadReturnValue Error");
}
pthread_join(ThreadOne, NULL); // waits until a thread is complete so that the program doesn't exit before thread execution
pthread_join(ThreadTwo, NULL); // waits until a thread is complete so that the program doesn't exit before thread execution
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment