Skip to content

Instantly share code, notes, and snippets.

@smallfish
Last active February 13, 2020 12:29
Show Gist options
  • Select an option

  • Save smallfish/b6a9305c906513e9ea33997022f38ae0 to your computer and use it in GitHub Desktop.

Select an option

Save smallfish/b6a9305c906513e9ea33997022f38ae0 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
void *test(int id) {
int r = 10 + rand() % 5;
printf("[%d] id: %d sleep(%d) start\n", getpid(), id, r);
sleep(r);
printf("[%d] id: %d sleep(%d) end\n", getpid(), id, r);
return NULL;
}
int main(int argc, char *argv[]) {
srand(time(NULL));
int N = 5;
if (argc == 2) {
N = atoi(argv[1]);
}
pthread_t tid[50000];
for (int i = 0; i < N; i++) {
pthread_create(&tid[i], NULL, test, i);
}
for (int i = 0; i < N; i++) {
pthread_join(tid[i], NULL);
}
printf("end");
return 0;
}
@smallfish
Copy link
Author

编译

$ gcc -o test_thread test_thread.c

运行(创建 2000 个线程)

$ ./test_thread 2000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment