如何解决 VS 中的 pthread.h 头文件问题
https://blog.csdn.net/qq_35292447/article/details/103541936
线程的创建
代码范例
#include <pthread.h>
#include <stdio.h>
void* say_hello(void* param);
int main(int args, char** argv) {
pthread_t tid;
pthread_create(&tid, NULL, say_hello, NULL);
pthread_join(tid, NULL);
printf("Hello from first thread\n");
return 0;
}
void* say_hello(void* param) {
printf("Hello from second thread\n");
return NULL;
}
参考资源
https://zhuanlan.zhihu.com/p/97418361
互斥锁
代码范例
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define ITERATIONS 1000000
void* runner(void* param);
int count = 0;
pthread_mutex_t lock;
int main(int argc, char** argv) {
pthread_t tid1, tid2;
if (pthread_mutex_init(&lock, NULL) != 0) {
printf("mutex init failed\n");
exit(1);
}
if (pthread_create(&tid1, NULL, runner, NULL)) {
printf("Error creating thread 1\n");
exit(1);
}
if (pthread_create(&tid2, NULL, runner, NULL)) {
printf("Error creating thread 2\n");
exit(1);
}
if (pthread_join(tid1, NULL)) {
printf("Error joining thread\n");
exit(1);
}
if (pthread_join(tid2, NULL)) {
printf("Error joining thread\n");
exit(1);
}
if (count != 2 * ITERATIONS)
printf("** ERROR ** count is [%d], should be %d\n", count, 2 * ITERATIONS);
else
printf("OK! count is [%d]\n", count);
pthread_exit(NULL);
pthread_mutex_destroy(&lock);
return 0;
}
void* runner(void* param) {
int i, temp;
for (i = 0; i < ITERATIONS; i++) {
temp = count;
temp = temp + 1;
count = temp;
}
return NULL;
}
参考资源
https://zhuanlan.zhihu.com/p/97512154
信号量
https://zhuanlan.zhihu.com/p/98717838
线程池
https://zhuanlan.zhihu.com/p/141615042
进程的创建
代码范例
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char** argv) {
pid_t root = getpid();
pid_t pid = fork();
printf("from %d forking into %d\n", root, pid);
sleep(20);
pid_t mypid = getpid();
pid = fork();
printf("from %d forking into %d\n", mypid, pid);
sleep(20);
if (getpid() == root) {
sleep(20);
printf("root exiting\n");
}
else {
printf("Child -- PID %d exiting\n", getpid());
}
return 0;
}
#include<unistd.h>
int main(int argc, char** argv) {
return execv("/usr/bin/ls", argv);
}
建立管道
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hello, world!\n";
char readbuffer[80];
pipe(fd);
if ((childpid = fork()) == -1) {
perror("fork");
exit(1);
}
if (childpid == 0) {
close(fd[0]);
write(fd[1], string, (strlen(string) + 1));
exit(0);
}
else {
close(fd[1]);
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
}
return (0);
}
|