将fork实现转换为pthread实现

时间:2018-04-02 21:26:18

标签: c pthreads

我试图将使用fork()的代码转换为线程。因为我需要变量值来改变。

使用fork()的代码:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

int value = 5;
int main(){
    pid_t pid;
    pid = fork();
    if(pid == 0){ //child process
        printf("Entrei no filho! \n");
        value += 15;
        return 0;
    }
    else if(pid > 0){ //parent process
        wait(NULL);
        printf("PARENT: value = %d\n", value);
        return 0;
    }}

最终值为5

我的尝试:

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

int main(int argc, char *argv[]){

    pthread_t thread1, thread2;
    char *msg1 = "First thread";
    char *msg2 = "Second thread";
    int value = 5;

    pthread_create(thread1, NULL, if1, (void *) msg1);
    pthread_create(thread2, NULL, if2, (void *) msg2);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    return 0;
}
void *if1(){
    value += 15;
    return NULL;
}
void *if2(){
    printf("Final value: %d",value);
    return NULL;
}

最终值必须是20使用线程

0 个答案:

没有答案
相关问题