【问题标题】:C multithreading with pthreadC 多线程与 pthread
【发布时间】:2017-04-03 14:12:59
【问题描述】:

我试图在一个循环中使用 pthread_create 创建 30 个线程。我使用了正确的标头。

struct student_thread{
int id;
char * message;
};


void *student(void *i)
{
struct student_thread *s;
s = (struct student_thread *) i;

printf("%s%d\n",s->message,s->id);
//sleep(1);
pthread_exit(NULL);
}



void creat_student_thread()
{
    pthread_t st[N];
    struct student_thread stt[N];

    int i,ct;

    for(i=0;i<N;i++){
        stt[i].id =i+1;
        stt[i].message = "Created student thread ";
        ct = pthread_create(&st[i],NULL,student,(void *) &stt[i].id);
        //enqueue(Q1,stt[i].id);
        if(ct){
            printf("Error!Couldn't creat thread\n");
            exit(-1);
        }
    }
}

int main()
{
    creat_student_thread();
}

但输出显示只创建了 28 个线程。output 我在这里错过了什么?提前致谢。

【问题讨论】:

  • N 定义在哪里?
  • 可能是输出刷新问题?请注意,您的一些线程报告创建乱序。尝试在student线程函数中的printf之后使用fflush(stdout);,看看是否更好看。
  • 另外,您将 &amp;stt[i].id 作为参数传递 - 这是一个 int *,但在线程中您将其转换为:(struct student_thread *) i;
  • creat_student_thread() 可以在任何创建的线程尝试通过 s 取消引用其值之前返回,因此使 stt 无效。然后 main() 退出,操作系统在终止进程时销毁所有线程。
  • 查找pthread_join()。你的main() 可以返回并导致你的程序在你的线程开始之前退出。

标签: c multithreading pthreads


【解决方案1】:

移动参数数组,'struct student_thread stt[N];'出“creat_student_thread()”。比如说,让它全球化。

防止 main() 提前退出,例如。带有无限睡眠循环或输入请求。

【讨论】:

    猜你喜欢
    • 2018-08-24
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 2011-05-12
    相关资源
    最近更新 更多