将来可以安全地传递到分离线程吗?

时间:2019-07-08 20:36:43

标签: c++ multithreading c++11

std::future传递到std::promise的分离实例是否安全?我知道在int main() { std::promise<void> p; std::thread( [f = p.get_future()]() { if ( f.wait_for( std::chrono::seconds( 2 ) ) == std::future_status::ready ) { return; } std::terminate(); } ).detach(); // wait for some operation p.set_value(); } 的下面有一个与DECLARE @typeId int = 175; DECLARE @item varchar(20)= 'ABC123' UPDATE table SET TypeId = @typeId WHERE item = @item 共享的shared_ptr中的状态。这是一个例子。

var request = require('supertest');
let should = chai.should();

require('../../boostrap.test.js');

describe('The bookedservices Controller', function() {
  let userRecord,
    studioRecord,
    serviceRecord,
    timingRecord,
    bookedServiceRecord,
    authenticatedUser,
    authenticatedStudio,
    session = null;

  before(async function() {
    // beforeEach(async function(done) {
    userRecord = await User.create({
      emailAddress: 'xx@gmail.com',
      password: 'xxisnotgood123',
      fullName: 'siddhant',
      location: 'vellore',
      image: 'not a pipi pic',
      mobile: '9681901311',
      description: 'words cant describe me'
    }).fetch();

    creditRecord = await Credits.create({
      expirydate: '2019-05-25T03:23:55.016Z',
      creditsPresent: 30,
      passType: '1 month',
      userId: userRecord.id
    }).fetch();

    studioRecord = await Studios.create({
      emailAddress: 'yy@gmail.com',
      password: 'yyisnotgood123',
      fullName: 'siddhant',
      location: 'vellore',
      image: 'not a lili pic',
      mobile: '9681901311',
      description: 'words cant describe me'
    }).fetch();

    serviceRecord = await Services.create({
      serviceName: 'zumba',
      price: 1500,
      creditCost: 3,
      studioId: studioRecord.id
    }).fetch();

    timingRecord = await Timings.create({
      eventInTime: '2019-05-11T03:23:55.016Z',
      eventOutTime: '2019-05-13T00:00:02.001Z',
      numberOfSlotsAvailable: 3,
      serviceId: serviceRecord.id
    }).fetch();

    bookedServiceRecord = await BookedServices.create({
      isComplete: 'false',
      bookingDate: '2019-05-13T03:23:55.016Z',
      timingId: timingRecord.id,
      userId: userRecord.id,
      studioId: studioRecord.id,
      serviceId: serviceRecord.id
    }).fetch();

    authenticatedUser = await request.agent(sails.hooks.http.app);
    authenticatedUser
      .post('/api/v1/users/entrance/login')
      .set('Accept', 'application/json')
      .send({ emailAddress: 'xx@gmail.com', password: 'xxisnotgood123' })
      .end((err, res) => {
        if (err) {
          throw err;
        } else {
          console.log(res);
          session = res.header['Sails.sid'];
        }
      });

    // authenticatedStudio = await request.agent(sails.hooks.http.app);
    // authenticatedStudio
    //   .post('/api/v1/studios/login')
    //   .set('Accept', 'application/json')
    //   .send({ emailAddress: 'yy@gmail.com', password: 'yyisnotgood123' });

    // done();
  });

  it('all the records have been added', function(done) {
    userRecord.should.have.property('id');
    console.log('OUTPUT: userRecord', userRecord);
    studioRecord.should.have.property('id');
    // console.log('OUTPUT: studioRecord', studioRecord);
    serviceRecord.should.have.property('id');
    // console.log('OUTPUT: serviceRecord', serviceRecord);
    timingRecord.should.have.property('id');
    // console.log('OUTPUT: timingRecord', timingRecord);
    bookedServiceRecord.should.have.property('id');
    // console.log('OUTPUT: bookedServiceRecord', bookedServiceRecord);

    done();
  });

  it('should post and return a bookedService model document', function(done) {
    timingRecordId = timingRecord.id;
    // console.log(`/api/v1/timings/${timingRecordId}/bookedservices`);

    authenticatedUser
      .post(`/api/v1/timings/${timingRecordId}/bookedservices`)

      .set('Accept', 'application/json')
      .set('Cookie', session)
      .send({ isComplete: false, bookedDate: '2019-05-13T00:10:02.001Z' })
      .expect(200)
      .expect('Content-Type', /json/)
      .end(function(err, result) {
        if (err) {
          done(err);
        } else {
          result.body.should.be.an('object');
          result.body.should.have.property('bookedServiceDoc');
          result.body.should.have.property('message');
          createdPostId = result.body.bookedServiceDoc.should.have.property(
            'id'
          );
          console.log(result.body);
          done();
        }
      });
  });

以上代码中存在潜在的错误情况,即在主线程退出之后执行lambda。主线程退出后,共享状态是否仍保留?

2 个答案:

答案 0 :(得分:2)

  

[basic.start.term] / 6 如果信号处理程序(21.10)中存在不允许使用的标准库对象或函数,则在(4.7)销毁完成之前没有发生对于具有静态存储持续时间并执行std::atexit个注册函数(21.5)的对象,该程序具有未定义的行为。

[basic.start.main] / 5 ,从main返回具有调用std::exit的效果,这确实会破坏具有静态存储持续时间的对象并执行{ {1}}个注册功能。因此,我相信您的示例展示了不确定的行为。

答案 1 :(得分:1)

根据cppreference

  

在典型的实现中,std :: shared_ptr仅保存两个指针:
  -存储的指针(由get()返回的指针);
  -指向控制块的指针。
  控制块是一个动态分配的对象...

鉴于此信息,我认为主线程的终止不会影响工作线程中的(sym-def (symbol "c") 4)