多線程

線程創建以及運行

#include <pthread.h>
 /* 創建子線程
  * 函數名: pthread_create
  * 參數:
  *     thread  保存新創建線程ID的變量地址值。線程與進程相同,也需要用於區分線程的ID。
  *     attr   用於傳遞線程屬性的參數,傳遞NULL時,創建默認屬性的線程。
  *     atart_routine 子線程開始執行的函數地址值。
  *     arg    傳遞線程調用函數時的包含參數信息的變量地址值
  * 返回值: 0成功,非0不成功
  */
  int pthread_create(pthread_t *restrict thread,
                       const pthread_attr_t *restrict attr,
                       void *(* start_routine)(void *),
                       void *restrict arg);
/* 銷燬子線程(調用該函數的進程或者線程將進入等待狀態,直到第一個參數ID的線程終止爲止)
 * 函數名: pthread_join
 * 參數:
 *     thread 該參數值ID的線程終止後纔會從該函數返回
 *     status 保存線程的main函數返回值(返回值的指針變量值)
 */
 int pthread_join(pthread_t thread, void ** status);

// 例子
// 子線程執行的函數
void* thread_main(void* arg)
{
    int count = *(int*)arg;
    char* msg = (char*)malloc(sizeof(char) * 50);
    strcpy(msg, "Hello,I'am thread~");
    for (int index = 0; index < count; ++index)
    {
        sleep(1);
        puts("running thread");
    }
    return (void*)msg;
}

int main(int argh,const char* argv[])
{
    pthread_t t_id;
    int pthread_param = 5;
    if(pthread_create(&t_id,NULL,thread_main,&pthread_param) != 0)
    {
        puts("pthread_create() error");
    }

    void* thread_result = NULL;
    if(pthread_join(t_id,&thread_result) != 0)
    {
        puts("pthread_join() error");
    }
    printf("Thread return message : %s\n",(char*)thread_result);
    free(thread_result);
    puts("end of main");
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章