Android Ndk 学习笔记(目录)
#include <iostream>
#include <vector>
#include <unistd.h>
#include <thread>
#include <pthread.h>
#include <queue>
using namespace std;
void runAction(int number){
for (int i = 0; i < 10; ++i) {
cout << number << endl ;
sleep(1);
}
}
void useThread(){
thread thread(runAction,100);
thread.join();
}
void * customPthreadTask(void * pVoid){
int * number = static_cast<int *>(pVoid);
cout << "异步线程执行了:" << *number << endl;
return 0 ;
}
void usePthread(){
int number = 1123;
pthread_t pthreadID;
pthread_create(&pthreadID,0,customPthreadTask,&number);
pthread_join(pthreadID,0);
}
queue<int> queueData;
pthread_mutex_t mutex ;
void * task(void * pVoid){
pthread_mutex_lock(&mutex);
cout << "异步线程-当前线程的标记是:" << *static_cast<int *>(pVoid) << "异步线程" << endl;
if (!queueData.empty()){
printf("异步线程-获取队列的数据:%d\n",queueData.front());
queueData.pop();
}else{
printf("异步线程-队列中没有数据了\n");
}
pthread_mutex_unlock(&mutex);
return 0 ;
}
void useTask(){
pthread_mutex_init(&mutex,NULL);
for (int i = 10000; i < 10011; ++i) {
queueData.push(i);
}
pthread_t pthreadIDArray[10];
for (int i = 0; i < 10; ++i) {
pthread_create(&pthreadIDArray[i],0,task,&i);
}
sleep(12);
pthread_mutex_destroy(&mutex);
}
#include "safe_queue_too2.h";
#ifndef C___SAFE_QUEUE_TOO2_H
#define C___SAFE_QUEUE_TOO2_H
#endif
#pragma once
#include <iostream>
#include <string>
#include <pthread.h>
#include <string>
#include <queue>
using namespace std;
template<typename T>
class SafeQueue2Class{
private:
queue<T> queue;
pthread_mutex_t mutex;
pthread_cond_t cond ;
public:
SafeQueue2Class(){
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
}
~SafeQueue2Class(){
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
void add(T t){
pthread_mutex_lock(&mutex);
queue.push(t);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
void get(T & t){
pthread_mutex_lock(&mutex);
while (queue.empty()){
pthread_cond_wait(&cond,&mutex);
}
t = queue.front();
queue.pop();
pthread_mutex_unlock(&mutex);
}
};
SafeQueue2Class<int> sq;
void * getMethod(void *){
while(true){
int value ;
sq.get(value);
if (-1 == value){
break;
}
}
return 0 ;
}
void * setMethod(void *) {
while (true) {
int value;
printf("请输入你要生成的信息:\n");
cin >> value;
if (-1 == value) {
sq.add(value);
break;
}
sq.add(value);
}
return 0;
}
int main(){
pthread_t pthreadGet;
pthread_create(&pthreadGet, 0, getMethod, 0);
pthread_t pthreadSet;
pthread_create(&pthreadSet, 0, setMethod, 0);
pthread_join(pthreadGet, 0);
pthread_join(pthreadSet, 0);
return 0 ;
}