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 1
#define B 0
#define C 0
#define D 0

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=(int *)malloc(1 * sizeof(int));
    b[0]=1111;
    pthread_exit((void*)(b));
#endif
#if B
    char *buf=(char *)malloc(sizeof(char)*32);
    strcpy(buf, "hello world123\n");
    pthread_exit((void*)buf);
#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));
#if A
    pthread_join( thread1, (void *)(&ret));
    printf("return value from thread = %d\n", *(int *)ret );
    free(ret);
#endif
#if B
    pthread_join( thread1, (void **)(&ret));
    printf("return value from thread = %s\n", (char *)ret );
    free(ret);
#endif
#if C
    pthread_join( thread1, (&ret));
    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
    pthread_join( thread1, (&ret));
    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

沒有留言:

張貼留言