c++学习笔记(pthread多线程参数同步)
多线程参数同步
#include "pch.h"
#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <assert.h>
#include <stdlib.h>
#include <Windows.h>
using namespace std;
#pragma comment(lib, "pthreadVC2.lib")
struct node_ {
int index;
char name;
}node;
void *test(void *arg)
{
int i;
node_ *pc = (node_*)arg;
pc->index = 5000;
//cout << << endl;
return NULL;
}
int main(int argc, char* argv)
{
pthread_t pId;
int i, ret;
node_ *ceshi=new node_;
ceshi->index = 5;
ceshi->name = 'sb';
//创建子线程,线程id为pId
ret = pthread_create(&pId, NULL, test, (void*)ceshi);
if (ret != 0)
{
printf("create pthread error!\n");
exit(1);
}
Sleep(10);
cout << ceshi->index;
printf("main thread will exit when pthread is over\n");
//等待线程pId的完成
pthread_join(pId, NULL);
printf("main thread exit\n");
return 0;
}
传递单个参数
#include "pch.h"
#include <iostream>
#include <stdio.h>
#include <pthread.h>
#include <assert.h>
#include <stdlib.h>
#include <Windows.h>
using namespace std;
#pragma comment(lib, "pthreadVC2.lib")
struct node_ {
int index;
char name;
}node;
void *test(void *arg)
{
int i;
int *pc = (int *)arg;
*pc = 10;
//cout << << endl;
return NULL;
}
int main(int argc, char* argv)
{
pthread_t pId;
int i, ret;
int a = 5;
int *ceshi= &a;
//创建子线程,线程id为pId
ret = pthread_create(&pId, NULL, test, (void*)ceshi);
if (ret != 0)
{
printf("create pthread error!\n");
exit(1);
}
Sleep(10);
cout << a;
printf("main thread will exit when pthread is over\n");
//等待线程pId的完成
pthread_join(pId, NULL);
printf("main thread exit\n");
return 0;
}
我就笑笑,笑他什么是非多端。
我就笑笑,笑他什么都看不穿。

浙公网安备 33010602011771号