Created
April 14, 2016 13:56
-
-
Save majecty/02abdf3212aceaf7f24bd87e401b47fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pthread.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
pthread_mutex_t mutex; | |
void error(const char* str) { | |
printf("str"); | |
exit(2); | |
} | |
void readFromFile(FILE* fp, char* buffer) { | |
char ch = '\0'; | |
int i = 0; | |
while ((ch = fgetc(fp)) != EOF) { | |
buffer[i] = ch; | |
i += 1; | |
} | |
buffer[i] = '\0'; | |
} | |
void writeFile(FILE* fp, char* buffer) { | |
rewind(fp); | |
fwrite("Output", sizeof(char), strlen("Output"), fp); | |
} | |
void *printHello(void *threadId) { | |
long tid; | |
tid = (long)threadId; | |
while (1) { | |
/*int result = pthread_mutex_trylock(&mutex);*/ | |
int result = pthread_mutex_lock(&mutex); | |
if (result != 0) { | |
printf("%ld: Try Lock Failed\n", tid); | |
} else { | |
break; | |
} | |
} | |
printf("%ld: Acquire lock!\n", tid); | |
printf("Hello World! %ld!\n", tid); | |
pthread_mutex_unlock(&mutex); | |
pthread_exit(0); | |
} | |
void createThread(long tid) { | |
pthread_t thread; | |
int rc = pthread_create(&thread, NULL, printHello, (void*)tid); | |
if (rc) { | |
printf("ERROR %d", rc); | |
exit(1); | |
} | |
} | |
int main(int c, char* argv[]) { | |
FILE* fp = fopen("data", "r+"); | |
if (fp == 0) { | |
error("file open Error"); | |
} | |
char buffer[256]; | |
readFromFile(fp, buffer); | |
printf("%s", buffer); | |
writeFile(fp, buffer); | |
pthread_mutex_init(&mutex, NULL); | |
pthread_mutex_lock(&mutex); | |
createThread(1); | |
createThread(2); | |
sleep(3); | |
pthread_mutex_unlock(&mutex); | |
sleep(1); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment