调用远程pthread函数时出现问题
大家好,
我使用pthread在C中编写了一些代码(我先在Eclipse IDE中配置了链接器和编译器).
Hi all,
I wrote some code in C using pthread (I configured the linker and compiler in Eclipse IDE first).
#include <pthread.h>
#include "starter.h"
#include "UI.h"
Page* MM;
Page* Disk;
PCB* all_pcb_array;
void* display_prompt(void *id){
printf("Hello111\n");
return NULL;
}
int main(int argc, char** argv) {
printf("Hello\n");
pthread_t *thread = (pthread_t*) malloc (sizeof(pthread_t));
pthread_create(thread, NULL, display_prompt, NULL);
printf("Hello\n");
return 1;
}
效果很好.但是,当我将函数display_prompt()
移到UI.h时,不会输出"Hello111"输出.
有人知道如何解决吗?
Elad
that works fine. However, when I move function display_prompt()
to UI.h no "Hello111 " output is printed.
Anyone knows how to solve that?
Elad
但是,当我移动函数display_prompt()时到UI.h
However, when I move function display_prompt() to UI.h
你动...什么?
您应该只将函数原型移至头文件.
但是,使用您提供的main
,输出(几乎)是不可预测的,因为 main
函数可能在线程有机会产生其输出之前就已经退出.
尝试以下代码:
You move...What?
You should move just the function prototype to the header file.
However, with the main
you provided, the output is (almost) unpredictable, since the main
function may exit well before the thread has a chance to produce its output.
Try this code:
/* ui.h */
void* display_prompt(void *id);
/* ui.c */
#include <stdio.h>
#include "ui.h"
void* display_prompt(void *id){
int i;
for (i=0;i<10; i++)
{
printf("Secondary thread %d\n", i);
sleep(2);
}
return NULL;
}
/* main source file */
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include "ui.h"
int main(int argc, char** argv) {
int i;
printf("Hello\n");
pthread_t *thread = (pthread_t*) malloc (sizeof(pthread_t));
if (!thread ) return -1;
pthread_create(thread, NULL, display_prompt, NULL);
for (i=0; i<10; i++)
{
printf("Main Thread %d\n", i);
sleep(1);
}
free(thread);
return 1;
}
:)
:)