请稍侯

POSIX线程编程

17 October 2015

POSIX的主要函数

int pthread_create (pthread_t *, const pthread_attr_t *,void *(*)(void *), void *);

应用代码:

/*
 * ph.c
 *
 *  Created on: 2012-10-14
 *      Author: defnone
 */

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5

//线程要执行的函数
void *PrintHello(void *threadid)
{
    long tid;
    tid = (long) threadid;
    printf("Hello World! It's me, thread #%ld!\n", tid);
    pthread_exit(NULL );
    return NULL;
}

int main(int argc, char *argv[])
{
    //定义线程数组
    pthread_t threads[NUM_THREADS];
    int rc;
    long t;
    for (t = 0; t < NUM_THREADS; t++)
    {
        printf("In main: creating thread %ld\n", t);
        /**
         * int pthread_create (pthread_t *, const pthread_attr_t *,void *(*)(void *), void *);
         * 参数:
         *     指向pthread_t的一个指针
         *     属性对象的指针
         *     要执行的函数
         *     函数的参数
         */
        rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
        if (rc)
        {
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }

    /* Last thing that main() should do */
    pthread_exit(NULL );
}