Linux   发布时间:2022-04-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了linux – 参数在pthread中传递错误大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

我编写了一个代码来打印出字符串:使用pthread将“Thread 0”改为“Thread 4”. 这是我的代码: 情况1: #include <stdio.h> #include <stdlib.h> #include <pthread.h> @R_618_6543@print_message_function(void* parameter) { long *i = (long *)parame
我编写了一个代码来打印出字符串:使用pthread将“Thread 0”改为“Thread 4”.

这是我的代码

情况1:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

@R_618_6543@print_message_function(void* parameter) {
    long *i = (long *)parameter;
    printf("Thread %ld\n",*i);
    pthread_exit(0);
}

int main(int argc,char *argv[]) {
    pthread_t threads[5];
    long i = 0;
    for (i = 0; i < 5; i++) {
        pthread_create(&threads[i],print_message_function,(@R_618_6543@)&i);
    }

    pthread_exit(null);
}

但结果是:

Thread 2
Thread 3
Thread 3
Thread 4
Thread 5

要么:

Thread 0
Thread 0
Thread 0
Thread 0
Thread 0

当我再次运行它时它改变了.所以我不知道为什么我传递的值是(2到5)或全部(0)或…..(很多情况).我想我通过的论点是从0到4.

案例2:

当我更改为新代码时:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

@R_618_6543@print_message_function(@R_618_6543@parameter);

int main(int argc,char *argv[]) {
    pthread_t threads[5];
    int i = 0;
    for (i = 0; i < 5; i++) {
        char *msg = (char*)malloc(sizeof(char));
        sprintf(msg,"Thread %d",i);
        pthread_create(&threads[i],(@R_618_6543@)msg);
    }
}

@R_618_6543@print_message_function(@R_618_6543@parameter) {
    printf("%s\n",(char *)parameter);
}

结果是:

Thread 1
Thread 0
Thread 3
Thread 2
Thread 4
Thread 4

这意味着循环运行了6次!为什么?

解决方法

将案例1更改为:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

@R_618_6543@print_message_function(void* parameter) {
    long i = (long)parameter;  // <<<
    printf("Thread %ld\n",i); // <<<
    pthread_exit(0);
}

int main(int argc,(@R_618_6543@)i); // <<<
    }

    pthread_exit(null);
}

您之前看到不一致结果的原因是因为您向每个线程传递指针,其中每个指针指向同一个局部变量,然后您正在修改该局部变量.

在案例2中,您只对一个字符进行malLocing,然后尝试将字符串写入其中.它应该很容易修复.

大佬总结

以上是大佬教程为你收集整理的linux – 参数在pthread中传递错误全部内容,希望文章能够帮你解决linux – 参数在pthread中传递错误所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。