java - C语言如何为特定任务编写像多线程一样的Java?它可以作为 objective-c 来完成吗?

标签 java c linux multithreading

我们如何创建多线程或进程?跨平台使用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/

相关文章:

java - 我需要在java中使用“符号

c - fork() 和 pipe() 的小问题

c - Linux C socket服务器printf问题

linux - ELF文件可以包含多个符号表吗?

linux - 如果进程之前已启动,如何阻止该进程启动?

java - 如何向超过 2 天未进入应用程序的用户发送推送通知?

java - 使用目录创建 excel 文件 Spring boot java

java - 从 onStopCommand 返回是否会结束 Android 服务?

访问 char 数组索引时出现 C 段错误

linux - getopts 不工作 - bash