四、使用NPTL进行线程编程
#include #include #include #include
void thread_fun(void * arg); char message[] = "I am created thread";
int main() { int rnt; pthread_t new_thread; void *thread_result; rnt=pthread_create(&new_thread,NULL, thread_fun, (void*) message);
if (rnt != 0) { perrer ("thread creation failed"); exit(EXIT_FAILURE); } printf("Waiting for other thread to finish…"); rnt = pthread_join(new_thread, &thread_result);
if (rnt != 0) { perrer ("thread join failed"); exit(EXIT_FAILURE); }
printf("Thread join, it returned %s ", (char*) thread_result); printf("message now %s", message); exit(EXIT_SUCCESS); }
void *thread_fun (void * arg) { printf("the new thread is running. Argument was %s",(char*)arg); sleep(3); strcpy(message, "Bye"); pthread_exit("Thank you for the test"); }
编译
gcc -D_REENTRANT test_thread.c -o test_thread -lpthread ./test_thread
成功了。
(参考链接: http://linux.ccidnet.com/art/741/20061123/958349_1.html)
|