Linux 멀티 스레드 프로그래밍 학습 코드(코드가 gitee에 업로드되었습니다. 별표를 클릭하세요!)
https://gitee.com/chenshao777/linux_thread.git
참고:
int pthread_create(pthread_t*restrict tidp,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void *),
void *restrict arg)
첫 번째 매개변수 : 새 스레드의 id, 성공하면 새 스레드의 id 스레드가 반환될 것입니다. tidp가 가리키는 메모리를 채우십시오.
두 번째 매개변수 : 스레드 속성(스케줄링 전략, 상속, 분리...) 세
번째 매개변수 : 콜백 함수(새 스레드가 실행할 함수)
네 번째 매개변수 : 콜백 함수의 매개변수
반환 값 : 성공 시 0 반환, 실패 시 오류 코드 반환
컴파일 시 라이브러리 pthread를 연결해야 합니다.
오류 코드
cat /usr/include/asm-generic/errno.h를 확인하십시오.
spu.h 파일
#ifndef _SPU_H_
#define _SPU_H_
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#endif
02.create_pthread.c 파일
#include "spu.h"
void print_id(char *str)
{
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid = %u, tid = 0x%x\n", str, pid, tid);
}
void *thread_fun(void *arg)
{
print_id(arg);
//return (void*)0;
}
int main()
{
int err;
pthread_t thread_id;
err = pthread_create(&thread_id, NULL, thread_fun, "new thread");
if(err != 0)
printf("create fail, err = %d\n",err);
else
printf("create success!\n");
sleep(1);
print_id("main_id: ");
return 0;
}