Untitled

mail@pastecode.io avatar
unknown
plain_text
3 months ago
1.4 kB
4
Indexable
Never
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

#define BUFFER_SIZE 1024

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int myfd;

void* thread_function1(void* arg) {
    
    char *buffer = arg;

    // Read from the pipe
    // pthread_mutex_lock(&mutex);
    write(myfd, buffer, sizeof(buffer));
    // pthread_mutex_unlock(&mutex);

    // Process the data
    printf("Thread %ld received: %s\n", pthread_self(), buffer);

    pthread_exit(NULL);
}

void* thread_function2(void* arg) {
    
    char *buffer = arg;

    printf("%s\n", buffer);
    // Read from the pipe
    // pthread_mutex_lock(&mutex);
    write(myfd, buffer, sizeof(buffer)); //critical section
    // pthread_mutex_unlock(&mutex);

    // Process the data
    printf("Thread %ld received: %s\n", pthread_self(), buffer);

    pthread_exit(NULL);
}

int main() {
    pthread_t thread1, thread2;

    myfd = open("new.txt",O_CREAT|O_RDWR);
    // Write to the pipe
    char message[] = "Hello 1!";
    char message2[] = "Hello 2!";

    // Create threads
    pthread_create(&thread1, NULL, thread_function1, &message);
    pthread_create(&thread2, NULL, thread_function2, &message2);

    // Wait for threads to finish
    // pthread_join(thread1, NULL);
    // pthread_join(thread2, NULL);

    // sleep(2);
    close(myfd);

    return 0;
}
Leave a Comment