我们如何创建多线程或进程?跨平台使用C语言?并在需要时关闭线程。一次编写部署Linux/Windows/Mac/Android/MeeGo等平台。
Java 示例: runnable = new Mytest();线程=新线程(可运行);
Step 1:
runnable = new Mytest();
thread = new Thread(runnable);
Step 2:
public class Mytest implements Runnable
{
private static volatile boolean running = true
public void run()
{
while(running)
{ // do stuff }
}
public void start() { running = true; }
public void stop() { running = false;}
}
跟进:
第一步:vim omp_hello.c ( https://computing.llnl.gov/tutorials/openMP/exercise.html )
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
int nthreads, tid;
#pragma omp parallel private(nthreads, tid)
{
/* Obtain thread number */
tid = omp_get_thread_num();
printf("Hello World from thread = %d\n", tid);
/* Only master thread does this */
if (tid == 0)
{
nthreads = omp_get_num_threads();
printf("Number of threads = %d\n", nthreads);
}
} /* All threads join master thread and disband */
}
第二步:$ gcc -fopenmp omp_hello.c -o hello
第 3 步:$ setenv OMP_NUM_THREADS 4
第四步:$./hello
Hello World from thread = 0
Number of threads = 4
Hello World from thread = 3
Hello World from thread = 1
Hello World from thread = 2
完成。它有效!
最佳答案
C语言中没有线程的概念。大多数平台都有自己特定的线程库或 API(显然有些平台根本不支持线程)。
但是,第 3 方库,例如 OpenMP存在,它在一定程度上提供独立于平台的线程。
关于java - C语言如何为特定任务编写像多线程一样的Java?它可以作为 objective-c 来完成吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5842899/