如何让两个C同时运行无限循环?
问题描述:
这两个周期必须同时工作,同时是无限的。我以前在Java和Python中做过这个,但是当我尝试在C中做这件事时,我遇到了一个问题。如何让两个C同时运行无限循环?
如果我这样做在Java中:
public static void main(String[] args)
{
new Thread(new Runnable()
{
@Override
public void run()
{
while (true)
{
// some code
}
}
}).start();
while (true)
{
// some code
}
}
或者在Python:
def thread():
while True:
# some code
def main():
t = threading.Thread(target = thread)
t.start()
while True:
# some code
if __name__ == '__main__':
main()
一切ok,但是当我做这在C:
void *thread(void *args)
{
while (1)
{
// some code
}
}
int main()
{
pthread_t tid;
pthread_create(&tid, NULL, thread);
pthread_join(tid, NULL);
while (1)
{
// some code
}
return 0;
}
只有循环在线程运行和编译器根本不会在创建线程后读取代码。那么如何做到这一点?
答
pthread_join
函数告诉调用线程等待,直到给定的线程完成。由于你开始的线程永远不会结束,main
永远等待。
摆脱该函数以允许主线程在启动子线程后继续。
int main()
{
pthread_t tid;
pthread_create(&tid, NULL, thread);
while (1)
{
// some code
}
return 0;
}
你知道'pthread_join'吗? –
pthread_join永远不会恢复,因为您的原始线程永远不会终止 – MrJman006
“...并且编译器在创建线程后根本不读取代码” - 现在,这是一个转折点。 –