Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <pthread.h>
- #include <unistd.h>
- void* watek(void* arg);
- FILE *plik;
- char buffor[100];
- pthread_mutex_t mutexDostepDoPliku;
- volatile int isBufferFull = 0;
- int main() {
- plik = fopen("buczko_mutex.c" , "r");
- if( plik == NULL )
- {
- fprintf(stderr, "Nie moge uzyskac dostepu do pliku");
- return -1;
- }
- pthread_mutex_init(&mutexDostepDoPliku, NULL);
- pthread_t watek1, watek2, watek3;
- pthread_attr_t atrybuty;
- pthread_attr_init(&atrybuty);
- pthread_attr_setdetachstate(&atrybuty, PTHREAD_CREATE_DETACHED);
- pthread_create(&watek1, &atrybuty, &watek, NULL);
- pthread_create(&watek2, &atrybuty, &watek, NULL);
- pthread_create(&watek3, &atrybuty, &watek, NULL);
- while (1) {
- pthread_mutex_lock(&mutexDostepDoPliku);
- if (fgets(buffor,100, plik) == NULL) break;
- isBufferFull = 1;
- pthread_mutex_unlock(&mutexDostepDoPliku);
- while(isBufferFull);
- }
- fclose(plik);
- return 0;
- }
- void* watek(void* arg)
- {
- pthread_t id = pthread_self();
- while(1) {
- if(isBufferFull)
- {
- pthread_mutex_lock(&mutexDostepDoPliku);
- if(isBufferFull) {
- printf("%ld:%s", id, buffor);
- isBufferFull = 0;
- }
- pthread_mutex_unlock(&mutexDostepDoPliku);
- }
- }
- return NULL;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement