线程于进程的对比
thread 线程 有共享内存 process 进程 没有共享内存 gcc file.c -lpthread 创建线程
#include <stdio.h> #include <pthread.h> void *myfunc(void *args) { for (int i = 0; i < 50; i++) { printf("%d\n", i); } return NULL; } int main() { pthread_t th1; pthread_t th2; pthread_create(&th1, NULL, myfunc, NULL); pthread_create(&th2, NULL, myfunc, NULL); pthread_join(th1, NULL); pthread_join(th2, NULL); return 0; } 传入参数
#include <stdio.h> #include <pthread.h> void *myfunc(void *args) { char *name = (char *)args; for (int i = 0; i < 50; i++) { printf("%s %d\n", name, i); } return NULL; } int main() { pthread_t th1; pthread_t th2; pthread_create(&th1, NULL, myfunc, "th1"); pthread_create(&th2, NULL, myfunc, "th2"); pthread_join(th1, NULL); pthread_join(th2, NULL); return 0; } 分部计算
...