如何在c中使用pthread调用函数? [英] How to call a function using pthread in c?

查看:59
本文介绍了如何在c中使用pthread调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 pthread 在单独的线程中调用函数?

How can I call a function in a separate thread using pthreads?

在 Java 中,答案如下:如何在Java中使用单独的线程调用方法?

In Java, the answer is as set out here: How to call a method with a separate thread in Java?

我如何在 C 中执行此操作?

How do I do this in C?

推荐答案

从技术上讲,你不能……至少不能直接.

Technically, you can't...at least not directly.

线程是处理器在运行程序时遵循的执行路径.在今天的环境中,多线程的实例很多.最终用户应用软件通常有不同的线程做不同的事情.然而,在服务器上,不同的线程正在做同样的事情,为客户端请求提供服务.在任何情况下,每个单独的线程都在以自己的堆栈帧和处理器状态运行.

A thread is an execution path that the processor is following as it runs your program. In today's environment, there are many instances of multiple threads. End-User application software generally has different threads doing different things. On a server however, different threads are doing the same thing which is serving client requests. In any case, each individual thread is running with its own stack frame and processor state.

如果您需要将数据传递给不同的线程进行处理,那么有两种方法可以做到:

If you need to pass data off to a different thread to be processed, then there are two ways to do that:

1) 以数据为参数创建一个新线程.

1) Just create a new thread with the data as an argument.

2) 使用工作队列安排.

2) Use a work-queue arrangement.

我会使用 #2,因为这样您就可以根据队列的设置方式运行多个生产者和消费者.

I would use #2 because then you can have multiple producers and consumers running depending on how the queue is setup.

以下是有关如何设置的几个示例:

Here's a couple of examples on how to set this up:

https://code.google.com/p/c-pthread-queue/source/browse/trunk/queue.c

http://williams.comp.ncat.edu/comp450/pthreadPC.c

这是一个关于 pthreads 的非常好的教程:https://computing.llnl.gov/tutorials/pthreads/

Here's a really good tutorial on pthreads: https://computing.llnl.gov/tutorials/pthreads/

希望这会有所帮助.

这篇关于如何在c中使用pthread调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆