25 Nisan 2021 Pazar

Threadlere özgü alanlar (pthread_key_create fonksiyonu)

 #include <string.h>

#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct tagPERSON {
    char name[32];
    int no;
} PERSON;
void *thread_proc1(void *param);
void *thread_proc2(void *param);
void foo(void);
pthread_key_t g_slotKey;
int main(void)
{
    pthread_t tid1, tid2;
    int result;
    if (pthread_key_create(&g_slotKey, NULL) != 0) {
        fprintf(stderr, "pthread_create: %s\n", strerror(result));
        exit(EXIT_FAILURE);
    }
    if ((result = pthread_create(&tid1, NULL, thread_proc1, NULL)) != 0) {
        fprintf(stderr, "pthread_create: %s\n", strerror(result));
        exit(EXIT_FAILURE);
    }
    if ((result = pthread_create(&tid2, NULL, thread_proc2, NULL)) != 0) {
        fprintf(stderr, "pthread_create: %s\n", strerror(result));
        exit(EXIT_FAILURE);
    }
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_key_delete(g_slotKey);
    return 0;
}
void *thread_proc1(void *param)
{
    PERSON *per;
    if ((per = (PERSON *)malloc(sizeof(PERSON))) == NULL) {
        fprintf(stderr, "cannot allocate memory!..\n");
        exit(EXIT_FAILURE);
    }
    strcpy(per->name, "Carol David");
    per->no = 333;
    pthread_setspecific(g_slotKey, per);
    foo();
    free(per);
    return NULL;
}
void *thread_proc2(void *param)
{
    PERSON *per;
    if ((per = (PERSON *)malloc(sizeof(PERSON))) == NULL) {
        fprintf(stderr, "cannot allocate memory!..\n");
        exit(EXIT_FAILURE);
    }
    strcpy(per->name, "Ferdinand Isaac");
    per->no = 765;
    pthread_setspecific(g_slotKey, per);
    foo();
    free(per);
    return NULL;
}
void foo(void)
{
    PERSON *per;
    per = (PERSON *)pthread_getspecific(g_slotKey);
    printf("%s, %d\n", per->name, per->no);
}

Share: