How to create multithread in C

#include <stdio.h>#include <pthread.h>#include <stdlib.h>static int count=0;void thread(void){ int i; count++; for(i=0; i<3; i++){ printf(“This is %d pthreadn”, count); }}int main(int argc, char* argv[]){ printf(“Hello worldn”); pthread_t id; int i, ret; ret = pthread_create(&id, NULL, (void *) thread, NULL); if(ret!=0){ printf(“Create pthread error!n”); exit(1); } for(i=0; i<20 ; i++){ printf(“This is main process~~n”); } pthread_join(id, NULL); return 0;}

補充:
1. create new thread:
extern int pthread_create __P ((pthread_t *__thread, __const pthread_attr_t *__attr,void *(*__start_routine) (void *), void *__arg));
pthread_create的參數裡分成四個部分,
第一個參數把宣告好的pthread丟進去,
第二個參數是更改原本pthread的預設屬性(pthread_attr),
第三個參數是thread要做的事,
第四個參數是thread要做的事所吃的參數
2. waiting process:
extern int pthread_join __P ((pthread_t __th, void **__thread_return));
第一個參數是main process要等待的thread,
第二個參數是thread的return值,把資源給回收回來
也可以使用pthread_exit()
3. 如何修改pthread的預設屬性? (pthread_attr)
#include <pthread.h>
pthread_attr_t attr;
pthread_t tid;

/*初始化属性值,均设为默认值*/
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);

pthread_create(&tid, &attr, (void *) my_function, NULL);

4. 如何更改thread的priority? (sched_param)
#include <pthread.h>
#include <sched.h>
pthread_attr_t attr;
pthread_t tid;
sched_param param;
int newprio=20;

pthread_attr_init(&attr);
pthread_attr_getschedparam(&attr, &param);
param.sched_priority=newprio;
pthread_attr_setschedparam(&attr, &param);
pthread_create(&tid, &attr, (void *)myfunction, myarg);
5. More:(看參考中的網址)
1) Mutual exclusive
2) Semaphore
參考:
1. Linux Multi-Thread programming:
https://sites.google.com/site/myembededlife/Home/applications–development/linux-multi-thread-programming

作者

RongSon

Graduate Student of CCU COMM Game Development, Network Communication, macOS/Ubuntu/Android, Arduino/Raspberry Pi/Intel Edison, Java/Python/C/C++

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *