2012年3月14日 星期三

pthread 基礎

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

typedef struct sa_t
{
    int c;
    char *d;
}ss;

#define A 0
#define B 0
#define C 0
#define D 1

void *test(void *a)
{
    ss s2;
    s2= *((ss *)(a));
    printf("c=%d\n", s2.c);
    printf("d=%s\n", s2.d);

#if A
    int *b=malloc(1 * sizeof(int));
    b[0]=1111;
    pthread_exit((void*)(b));
#endif
#if B
    pthread_exit((void*)2);
#endif
#if C
    pthread_exit((void*)"hello");
#endif
#if D
    ss *s3=malloc(sizeof(s3));
    s3->c=3333;
    s3->d="hi";
    pthread_exit((void*)(s3));
#endif
}
int main (void)
{
    pthread_t thread1;
    ss s1={20, "hello"};
    void *ret;

    pthread_create(&thread1, NULL , test , (void *)(&s1));
    //pthread_join( thread1, (void *)(&ret));
    pthread_join( thread1, (&ret);
#if A
    printf("return value from thread = %d\n", *(int *)ret );
#endif
#if B
    printf("return value from thread = %d\n", *(int *)ret );
#endif
#if C
    char a[16];
    strcpy(a, (char *)(ret));
    printf("return value from thread = %s\n", a );
    printf("return value from thread = %s\n", (char *)(ret) );
#endif
#if D
    ss s3;
    s3= *((ss *)(ret));
    printf("cc=%d\n", s3.c);
    printf("dd=%s\n", s3.d);
#endif
    return 0;
}
Compiler: gcc xx.c -o xx -lpthread

沒有留言:

張貼留言