android中和c++中生产者和消费者模式

本文通过一个示例详细讲解了在Android和C++中如何使用synchronized关键字和std::mutex结合std::condition_variable进行线程同步。在Android部分,通过一个按钮触发线程,线程中使用随机数模拟数据生成,再通过notify唤醒等待的线程;C++部分则使用了std::mutex和std::condition_variable实现类似的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先上代码,android

package com.wmz.helloworld;
import java.util.Random;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Demo extends android.app.Activity {
	private class Token {
		private String flag;
		public Token() {
			setFlag(null);
		}
		public void setFlag(String flag) {
			this.flag = flag;
		}
		public String getFlag() {
			return flag;
		}
	}
	private Token token = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.demo);
		Button btn = (Button) findViewById(R.id.button1);
		token = new Token();
		if(token.getFlag() ==null)
			Log.v("A","the token flag value is null");
		else
			Log.v("A","the token flag value is"+token.getFlag());
		btn.setOnClickListener(new OnClickListener() {			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				WorkThread workthread = new WorkThread();
				workthread.start();	
				Random r=new Random();
				for (int i = 0;i<10; i++) {
					try {						
						Thread.sleep((r.nextInt(9)+1)*1000);		//增加不确定性,至少睡眠1秒
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized (token) {
						token.setFlag("wangmz"+Integer.toString(i));
						token.notifyAll();
						Log.v("Main",Integer.toString(i));
					}					
				}
			}
		});		
	}
 
 
	private class WorkThread extends Thread {
		@Override
		public void run() {
			Random r=new Random();
			while (true) {				
//				try {
//					Thread.sleep((r.nextInt()+1)*1000);//可能在sleep的时候其他线程执行notify()。但此时对这个线程不起作用。所以结果不会按顺序出现
//				} catch (InterruptedException e1) {
//					e1.printStackTrace();
//				}
				synchronized (token) {
						try {
							token.wait();
							Log.v("Main", "the value is " + token.getFlag());
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
				}
				Log.v("work","while!!");
			}
		}
	}
}

c++中实现

std::mutex img_mutex_;
std::condition_variable img_cv_;

cv::Mat camera::grapPicture()
{
    std::unique_lock<std::mutex> lk(img_mutex_);
    img_cv_.wait(lk,[this]{return this->isReady_;});
    cv::Mat temp= img_.clone();
    std::cout<<"grap picture,img size:"<<temp.rows<<","<<temp.cols<<std::endl;
    isReady_=false;
    return temp;
}


void camera::work_loop()
{
    while(isRunning)
    {
        {
            std::lock_guard<std::mutex> lk(img_mutex_);
            (*capture_)>>img_;
            isReady_=true;
        }
        img_cv_.notify_one();
        if(onpreviewcb_)
            onpreviewcb_(img_);
        //if here don't sleep,this thread will lock img_mutex_ in all most time,and grapPicture will have not chance to grap image
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
    std::cout<<"camera:work_loop end"<<std::endl;
}

可以看到,两者基本是一样的,消费者首先要获得同步锁,然后wait(wait内部会释放同步锁),生产者这时候获得同步锁,生产数据,notify,释放同步锁(如果不释放,消费者是无法执行的),这时候消费者在wait处又可以开始执行了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值