日期:2014-05-16  浏览次数:20572 次

一个linux线程编程的问题。。
C/C++ code

#include<pthread.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>

void* routine(void *arg)
{
    printf("main said to routine:%s\n",(char *)arg);
    pthread_exit((void*)0);
}

int main()
{
    int ret;
    pthread_t mythread;
    ret = pthread_create(&mythread,NULL,routine,"hello world");
    printf("ret is %d\n",ret);
    if(ret != 0)
    {
    printf("Could not create thread: %s\n",strerror(errno));
    exit(-1);
    }
    return 0;
}



这个程序输出的结果是:
ret is 0
main said to routine:hello world
main said to routine:hello world

我知道可能是主线程没有等待其他线程执行完毕的原因,因为我要是去掉 printf("ret is %d\n",ret); 结果是什么都不输出的。
请教大神们为什么会输出两行 “main said to routine:hello world”。

------解决方案--------------------
我刚运行了下,有几个问题:1:pthread_create最后一个参数应该是(void *)类型;2.main函数要等待线程结束再结束,不然线程不能执行完整。最好加个pthread_join();3.线程和mian函数是同步的,哪个先执行完,无法预知。至于你出现的两个main said to routine:hello world;这个应该跟你的系统相关,我并没有出现这种情况。
------解决方案--------------------
粗略一看,先说一句,printf不是线程安全的。
------解决方案--------------------
试试:
char *str = "Hello world";
ret = pthread_create(&mythread,NULL,routine,str);
sleep(1);