C:
/* Thread.c */
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#define N 50
void* tproc(void *arg) {
printf("Thread %d\n", *((int *) arg));
sleep(3);
return NULL;
}
int main(int argc, char * argv[]) {
int i;
int targ[N];
pthread_t tid[N];
for(i = 0; i < N; i++) {
targ[i] = i*i;
if(pthread_create(&(tid[i]), NULL, &tproc, &targ[i]) != 0) {
printf("Can't create thread %d\n", i);
return 1;
}
}
for(i = 0; i < N; i++) {
if(pthread_join(tid[i], NULL) != 0) {
printf("Can't join thread %d\n", i);
}
}
return 0;
}
/* Please note that the checks on the return value of the system calls
have been omitted to avoid cluttering the code. However, system calls
can and will fail, in which case the results are unpredictable. */
Java:
import java.util.concurrent.*;
class MyThread extends Thread {
static final int N = 50 ;
int arg;
public MyThread(int arg) {
this.arg = arg;
}
public void run() {
System.out.println("Thread " + arg);
}
public static void main(String [] args) {
MyThread[] tid = new MyThread [N] ;
for(int i = N-1; i >= 0; i--) {
tid[i] = new MyThread(i*i);
tid[i].start();
}
for(int i = 0; i < N; i++) {
try { tid[i].join(); }
catch(InterruptedException e) { }
}
}
}
我使用Linux Time命令运行两个程序,并得到以下结果:
C:真正的0m3.015s用户0m0.001ssys 0m0.026s
Java:真正的0m0.278s用户0m0.178ssys 0m0.115s
我的系统信息是:Linux 4.19.75-v7l + armv7l看来Java版本比C版本快得多,这可能是背后的原因吗?
您的C线程睡眠3秒钟,您的主线程等待它们(使用pthread_join
)。
在tproc()
函数中,您发出对sleep(3)
的调用,因此线程休眠3秒钟。因此,pthread_join()
必须等待它们唤醒才能加入它们。 Java代码不执行此操作。另外,看看C中的sys
和user
时间,它们比Java中的时间少得多,这意味着您在C中消耗的CPU时间更少。因此,唯一的延迟是由于线程处于休眠状态。