歡迎您光臨本站 註冊首頁

linux多線程的總結(pthread用法)

←手機掃碼閱讀     火星人 @ 2014-03-26 , reply:0

原創:lobbve223

#include
int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr,
void *(*start_rtn)(void),void *restrict arg);
Returns: 0 if OK, error number on failure

第一個參數為指向線程標識符的指針。

第二個參數用來設置線程屬性。

第三個參數是線程運行函數的起始地址。

第四個參數是運行函數的參數。

當創建線程成功時,函數返回0,若不為0則說明創建線程失敗,常見的錯誤返回代碼為EAGAIN和EINVAL。前者表示系統限制創建新的線程,例如線程數目過多了;後者表示第二個參數代表的線程屬性值非法.
pthread_create的用法:由於pthread庫不是Linux系統默認的庫,所以在使用pthread_create創建線程時,需要在編譯中請加-lpthread參數,eg:gcc -o test -lpthrea test.c

例1:

#include "pthread.h"
#include "stdio.h"
void* thread_test(void* ptr)
{ while(1)
printf("i am pthread\n");
}
int main()
{
pthread_t pid;
pthread_create(&pid, NULL, test_thread, NULL);
while(1)
printf("i am main pthread\n");
return 0;
}

例2:

#include
#include
pthread_t id;
int ret;
void thread_1()
{
while(1)
{printf(「I am thread\n」);
sleep(1);
}
}
main()
{ret = pthread_create(&id,NULL,(void*)thread_1,NULL);
if(ret != 0)
printf("Create pthread error!\n");
while(1)
{
printf(「I am main thread\n」);
sleep(2);
}
}

例3:

#include
#include
#include
#include
void *thread_function(void *arg);
char message[] = "Hello World";
int main()
{
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_create(&a_thread, NULL, thread_function, (void *)message);
if (res != 0)
{
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
printf("Waiting for thread to finish...\n");
res = pthread_join(a_thread, &thread_result); //pthread_join 阻塞執行的線程直到某線程結束
if (res != 0)
{
perror("Thread join failed");
exit(EXIT_FAILURE);
}
printf("Thread joined, it returned %s\n", (char *)thread_result);
printf("Message is now %s\n", message);
exit(EXIT_SUCCESS);
}
void *thread_function(void *arg)
{
printf("thread_function is running. Argument was %s\n", (char *)arg);
sleep(3);
strcpy(message, "Bye!");
pthread_exit("Thank you for the CPU time");
}
[root@plinux tmp]# cc -D_REENTRANT -I/usr/include/nptl thread2.c -o thread2 -L/usr/lib/nptl -lpthread
[root@plinux tmp]# ./thread2
thread_function is running. Argument was Hello World
Waiting for thread to finish...
Thread joined, it returned Thank you for the CPU time
Message is now Bye!
pthread_join()
void pthread_exit(void *retval)
int pthread_join(pthread_t pid, void **thread_return)

pthread_join()的調用者將掛起並等待th線程終止,retval是調用pthread_exit()的線程(線程ID為pid)的返回值,如果thread_return不為NULL,則*thread_return=retval。

需要注意的是一個線程僅允許唯一的另一個線程使用 pthread_join()等待本線程的終止,並且被等待的線程應該處於可join狀態,即非DETACHED狀態。

[火星人 ] linux多線程的總結(pthread用法)已經有8764次圍觀

http://coctec.com/docs/linux/show-post-186555.html