【发布时间】:2021-08-15 03:38:39
【问题描述】:
我是操作系统的完整初学者。我遇到的问题是我想从线程接收一个值到主进程。一个垃圾值被打印在 main 中。请详细说明,以便我知道我的错误。
这是我的代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <iostream>
#include<string.h>
#include <sys/wait.h>
#include<pthread.h>
#include <sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
#include<time.h>
#include <fstream>
#include<vector>
using namespace std;
void *thread_1(void *arg);
int main(int argc, char* argv[])
{
void *temp;
pthread_t t1;
pthread_create(&t1, NULL,thread_1,NULL);
pthread_join(t1,&temp);
int *num = (int*)temp;
cout<<"Value in main: "<<*num<<endl;
}
void *thread_1(void *arg)
{
int number = 5;
int* value = &number;
cout<<"Value in thread: "<<*value<<endl;
pthread_exit((void*)value);
}
【问题讨论】:
-
可以更改我的代码并在此处分享吗?我试过但没有帮助....同样的问题:(
-
您正在发出一个指向堆栈上项目的指针,该项目在指针被取消引用时将不存在。停止这样做,最好完全停止使用 join()。
标签: c++ linux multithreading operating-system